Luke
Luke

Reputation: 1673

What are Subscriptions in RxJS and how do Observables interact with them?

I don't have it very clear on how Observables and Subscriptions work. In particular how an Observable and its Subscriptions exchange information.

So to make explicit questions:

Upvotes: 0

Views: 849

Answers (2)

ggradnig
ggradnig

Reputation: 14149

A Subscription is the result of an Observer getting added to an Observable. It is an object that can only be used to unsubscribe from that Observable. When unsubscribed, the Observer won't receive any further emissions.

The Observer (which you might be referring to as Subscription) is what gets created when you call Observable.subscribe(next, error, complete). You'll receive the Observer when implementing your own Observable with Observable.create(). Otherwise, you won't get a hold of it. The Observer holds the next(value => void), error(error => void) and complete(_ => void) functions that are used by the Observable to communicate state changes.

Exchanging information only happens in one direction. The Observable always emits to the Observer, never the other way round.

Now for your questions:

Does an Observable keep references to its Subscriptions?

No, it keeps references to its Observers, but that's probably what you mean.

Does a Subscription keep a reference to the Observable that created it?

No, only a function that is used for unsubscribing from that Observable. An Observer also doesn't have a reference to the Observable that it's subscribed to.

Does an Observable "put" data in its Subscriptions or does a Subscription "poll" its Observable?

The Observable "puts" (better word would be "emits") values to its Observers. There is never any polling from an Observable, as this would violate the fundamental principal of RxJS. One exception would be BehaviourSubject.getValue(), but you shouldn't use that in most cases!

How does the information exchange happen?

It depends on the Observable. Generally, an Observable holds a list of all its Observers and calls their next() functions whenever a new value is emitted, the error() function when an error occurs and the complete() function when it reached its completeness state.

Upvotes: 4

LkPark
LkPark

Reputation: 566

Basically, your question is related to a more general observer pattern, here is a good article about this in JS example or more general use example you will get all your answers.

Upvotes: 1

Related Questions