user3591466
user3591466

Reputation: 867

How to make an observable share across subscribers in angular 4?

Consider the following code

getObservable() {
    return this.http.get('get_something').map(
        data => {
            return true;
        },
        err => {
            return false;
        }
    );
}

subscriber_1 = this.getObservable().subscribe(
    data => {
        console.log("from subscriber 1", data);
    }
);

subscriber_2 = this.getObservable().subscribe(
    data => {
        console.log("from subsriber 2", data);
    }
);

for (var _i = 0; _i < 100; _i++) {
    this.getObservable()
}

I expect from subscriber 1 and from subsriber 2 to get print 100 times. However it is only printed 1 time.

I thought observables are vectors and not scalars, so that anytime the same observable is invoke it will invoke all subscribers?

I must be doing something wrong.

Can someone help out?

Thanks

Upvotes: 0

Views: 960

Answers (1)

Bogdan Bogdanov
Bogdan Bogdanov

Reputation: 386

Here is what you do:

  1. You create a function which creates a request and returns some value.
  2. The first subscriber subscriber_1 is making the request and when you call the subscribe function is waiting only for the current request to receive a response.
  3. When you do the loop you are just making a request. You are not doing anything to handle the response to these requests.

So far from what I understand you want to use a Subject from RxJS.

let subject: Subject<any> = new Subject<any>();

// Anytime the subject value is changed a notification is triggered 
// The subscribe function is handling it 
let subscriber_1 = subject.AsObservable().subcribe((data) => {
  console.log(data);
  return data;
})

// Trigger a notification 100 times
for(let i = 0; i < 100; i++) {
   subject.next(i);
}

Here is an one good article where you can understand more about Subject class https://medium.com/@benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93

Or

If you don't want to use a RxJS you have to implement an observable pattern.

http://www.dofactory.com/javascript/observer-design-pattern Here is one good explanation with an example.

Upvotes: 1

Related Questions