Hello,
Is it possible to have multiple subscriptions on a same observable? e.g:
Observable obs = <perform values computation>
Subscription sub1 = obs1.subscribe(...)
Subscription sub2 = obs2.subscribe(...)
From what I have understood, each time obs.subscribe(...) is called a new Observable is created. That leads to the fact the computation in obs is performed each time sub1 and sub2 subscribe.
The computations in obs are quite heavy and I would like compute them once and feed the results to both sub1 and sub2. Is this behaviour achievable?
Thank you,
Best regards,
Sure, use source.publish().refCount(). The computation runs once and everyone gets notified at the end.
If you don't like the sound of that we added obs = obs.share() to wrap the .publish().refCount(). This has one gotcha. If the source observable is asynchronous the first subscription could get a more values than the second subscription. A much safer way to do it is to the ConnectableObservable connObs = obs.publish() returned by publish method to connObs.connect() after all of the subscriptions have been completed.
Observable obs = <perform values computation>
ConnectableObservable connObs = obs.publish()
Subscription sub1 = connObs.subscribe(...)
Subscription sub2 = connObs.subscribe(...)
connObs.connect()
Or the publish overload that takes a function so you do your logic within the function and it worries about connecting everything.
It is often far better than dealing with ConnectableObservable directly.
Closing due to inactivity. If you have further questions, don't hesitate to reopen this issue or create a new one.
Most helpful comment
If you don't like the sound of that we added
obs = obs.share()to wrap the.publish().refCount(). This has one gotcha. If the source observable is asynchronous the first subscription could get a more values than the second subscription. A much safer way to do it is to theConnectableObservable connObs = obs.publish()returned by publish method toconnObs.connect()after all of the subscriptions have been completed.