Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several observables chain together to accomplish

Tags:

rx-java

I need to use 1st observable result to create 2nd observable and subscribe to its result, and sometimes it requires 3 to 4 layers of observables. What are the best approaches to complete this?

like image 990
angelokh Avatar asked Dec 02 '25 02:12

angelokh


1 Answers

If you are simply chaining them and using the 4th Observable as a result, you can simply use the objects directly and everything will work fine (assuming you are using Scala here) :

val obs1 = Observable.interval(1 second)
val obs2 = obs1.map(_*2)
obs2.subscribe(println(_))

On the other hand, if obs1 is a data feed and you need several separate subscriptions, this will not work because all data will be consumed by the first subscription. So this code will do exactly the same :

val obs1 = Observable.interval(1 second)
val obs2 = obs1.map(_*2)
obs2.subscribe(println(_))
obs2.subscribe(println("I am never executed !"))

In that case, you will have to convert this (cold) Observable to an hot Observable, i. e. a Subject.

val s = new Subject()
s.onNext("I am a value")
...
s.subscribe(println("first print : "+_))
s.subscribe(println("second print : "+_))

Here all subscribers will receive data.

Here is an example of a complex code where you have a Subject of Observables that are Twitter feeds for specific keyword. This is a Subject to let several Observables subscribe to it and then do completely different things in parallel in different Observables.

like image 165
ffarquet Avatar answered Dec 03 '25 15:12

ffarquet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!