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?
To have multiple functions subscribe to a single Observable, just subscribe them to that observable, it is that simple. And actually that's what you did.
RxSwift: Subscribing to Observables It is the subscription that triggers an observable to begin emitting events until . error or . completed is emitted. Observing an observable is known as subscribing. Subscribe takes an escaping closure that takes an event of the supplied typed (that doesn't return anything).
In (very) simple terms, share passes a ReplaySubject to multicast. Internally, the subject is subscribed to the source observable (the underlying subscription) and its emitted values are handed to the subject, which in turn passes the values to the actual subscribers.
Therefore, an video (event of Observable) is shown on viewers(Observer), viewers(Observer) can action for each videos(event of subscribed Observable). In ReactiveX, an Observer subscribes an Observable, and then observer reacts whatever item or sequence of items the Observable emits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With