Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit an event manually in RxSwift

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.

like image 671
dummy307 Avatar asked Mar 16 '16 17:03

dummy307


1 Answers

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.

like image 101
tomahh Avatar answered Oct 05 '22 02:10

tomahh