Reputation: 714
I understand that if I want to have multiple subscriptions to one observable I need to use .share() operator, but I do not understand why exactly?
I looking for some example based on local data (not network) to demonstrate what is the difference between using .share() and without it.
What's the operator really do - using data from previous subscription or create new one?
Upvotes: 10
Views: 8151
Reputation: 2259
I've written a small fictional example:
let shareObservable = Observable<Int>.create { observer in
print("inside block")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
observer.onCompleted()
}
return Disposables.create()
}.share()
shareObservable.subscribe()
shareObservable.subscribe()
with the following output:
inside block
If I remove .share
from the shareObservable
I will see:
inside block
inside block
The main point of this example is that I subscribe to the same observable
the second time that is not completed yet and so the logic inside the block won't be executed.
Let me know if you have some misunderstandings by now.
You can read more about share
, shareReplay
, shareReplayLatesWhileConnected
, etc.
Upvotes: 21