Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually send next signal to a observable in RxSwift?

I create an observable using the following code:

let disposeBag = DisposeBag()

let myJust = { (element: String) -> Observable<String> in
    return Observable.create { observer in
        observer.on(.next(element))
        //observer.on(.completed)
        return Disposables.create()
    }
}

That code comes from RxSwift's sample code.

If I create an empty Observable myJust, and later I try to send it a value:

myJust("🔴").on(.completed)

I get the following error:

error: value of type 'Observable<String>' has no member 'on'
like image 273
leizh00701 Avatar asked Sep 12 '16 12:09

leizh00701


People also ask

What is onNext in RxSwift?

parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence.

What is subscribe in RxSwift?

The Subscribe is how you connect an observer to an Observable. onNext This method is called whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. When a value is added to an observable it will send the next event to its subscribers.

What is observer in RxSwift?

Observables: Observables is basically a wrapper around some data source and data source typically means a stream of values, since the main purpose of using RxSwift to do async programming easily, data coming from different sources over time will be put in this stream and will send to the observers.

When should I use RxSwift?

RxSwift helps when you need to combine complex asynchronous chains. RxSwift also has types such as Subject, a kind of bridge between the imperative and declarative worlds. The subject can act as an Observable, and at the same time, it can be an Observer, i.e. accept objects and issue events.


1 Answers

You can't. Observables can only be observed. If you want to push values, you'll need a Subject. A Subject is both an Observable and an Observer so it can emit and listen to Events. In RxSwift you can also create a Variable which you can bind an Observable to.

Quick example for BehaviorSubject:

let subject = BehaviorSubject(value: 1)
subject.on(.Next(2))
subject.on(.Next(3))
subject.on(.Completed)
like image 90
Luka Jacobowitz Avatar answered Sep 19 '22 18:09

Luka Jacobowitz