ssougnez
ssougnez

Reputation: 5876

Creating my own observable with rxjs and angular2

I have two components on the same page. The first one displays a list of item while the second one is a refiner for the displayed items. I'd like to use Observables in a service in order to establish a "communication" between the two components.

So, in my mind, it would be something like:

It seems simple but I can't wrap my head around the different classes (Subscription, Subscriber, Subject and Observable). The closest I've been was by using Subject but I have no idea how to send the initial list of items when there is a new subscriber.

Upvotes: 2

Views: 228

Answers (1)

magnattic
magnattic

Reputation: 12998

You are on the right track. If you want every subscriber to get the previously emitted values, use a ReplaySubject. This will replay the whole list (or whatever buffer length you chose) to every new subscriber.

If you have a fixed start value for the ReplaySubject, use a BehaviorSubject.

You want to use one of those two as a private property within your service. When you call the service with a new list, call .next on the Subject. Add a public getter method for the Subject where you convert it to an Observable (with the .asObservable() method). This is used for subscribers to get the values. (You don't want to make the Subject itself public to prevent others from changing it.)

A Subject is an Observable and an Observer at the same time, which means you can not only get values from it (via the Observable interface), but also add those values yourself (via the Observer interface).

Upvotes: 1

Related Questions