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

leizh00701 picture leizh00701 · Sep 12, 2016 · Viewed 8.9k times · Source

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'

Answer

Luka Jacobowitz picture Luka Jacobowitz · Sep 12, 2016

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)