Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift multiple subscriptions to one observable

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?

like image 789
Mr. A Avatar asked Jul 16 '17 12:07

Mr. A


People also ask

Can an observable have multiple subscribers?

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.

What is subscribe in RxSwift?

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).

What is share in RxSwift?

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.

What is observer in RxSwift?

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.


1 Answers

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.

like image 53
Nikita Ermolenko Avatar answered Oct 07 '22 13:10

Nikita Ermolenko