Emit an event manually in RxSwift

dummy307 picture dummy307 · Mar 16, 2016 · Viewed 11.1k times · Source

I'm a newbie in RxSwift and need a very basic help.
Assump that I have an Observable and subscribe it like this.

 let source: Observable<Void> = Observable.create { [weak self] observer in

        guard let _ = self else {
            observer.on(.Completed)
            return NopDisposable.instance
        }

        observer.on(.Next())

        return AnonymousDisposable {

        }
    }

And the subscribe like this:

 source.subscribeNext { () -> Void in

    }

The question is: how can I emit the event to subscribeNext manually every time I need. This is like rx_tap behavior on UIButton.
I see in the example code has something like this source = button.rx_tap.asObservale(). After that, every time user tap to button, there will emit an event and trigger on subscribeNext(). I also want to have that behavior but in programmatically, not from UI event.

Answer

tomahh picture tomahh · Mar 16, 2016

Most of the time, you can compose your observable and the solution I'm about to give is not the recommended way to do Rx code.

You can look at Subject to implement the behavior you request. There are multiple variations on subject, that the documentation explains well.

An example usage, inspired from RxSwift's playground:

let subject = PublishSubject<String>()

_ = subject.subscribeNext { content in
    print(content)
}
subject.on(.Next("a"))
subject.on(.Next("b"))

This will print "a" then "b".

For more detail about when to use subject or not, I'd recommend reading this article.