When would I not want to share a subscription?

After reading the example in chapter 6 (page 117 in RxSwift_v1.1), it seems to me that almost all subscriptions should be shared. Is this a valid thought and if so, in what scenarios would I not want to share a subscription?

@ultimatefilipino. Thanks very much for your question!

I took a look, and found the following paragraph that might help answer your question:

The rule of thumb about sharing operators is that it’s safe to use share() with observables that do not complete, or if you guarantee no new subscriptions will be made after completion. If you want piece of mind use share(replay: 1) - you’ll learn more about this in Chapter 8, “Transforming Operators in Practice.”

So my guess would be to share in the above circumstances.

I hope this helps!

All the best!

hey @ultimatefilipino, in many (if not most) cases sharing an observable sequence to many observers is what you want. The main point here is that the first subscription is the one creating the observable and therefore performing the side effects - for example in the case you are uploading a file and you’re observing the progress of the upload. Let’s imagine you have a function uploadFile(filePath: String) -> Observable<Double> which takes a file path and uploads a file while emitting the upload progress as Double values. In this case each time you call uploadFile() you’re effectively uploading one more file, while if you use share() on a sinlge uploadFile() then you’re uploading one file but sharing the progress with more observers… I hope this example is useful

1 Like

Let me see if I can sum this up in an if/else block

if obserableHasNoSideEffects || onlyRunObservableOnce {
// share observable
} else {
// don’t share observable
}

Is that correct?

yeah that sounds good to me

Thanks so much for your help!

This topic was automatically closed after 166 days. New replies are no longer allowed.