Mathius Mathius - 2 months ago 14
Javascript Question

RxJs: How to "listen" to change on a subscription when it receives a stream?

I'm new with Angular 2 and Observables, but I haven't found a way to "listen" to change on a subscription when it receives a stream, I don't even know if this is possible or if it's the right way.

This is what I used to do with promises:

// Constructor and more code
// ...

ngOnInit(): void {
this.loading.present();

this.getItems()
.then(() => this.loading.dismiss());
}

getItems(): Promise {
return this.itemService
.getItems()
.then(items => this.items = items);
}

refresh(refresher): void {
this.getItems()
.then(() => refresher.complete());
}


I've tried it with subscription/observables but I just don't know how:

// Constructor and more code
// ...

ngOnInit(): void {
this.loading.present();

this.getItems()
.subscribe(() => this.loading.dismiss());
}

getItems(): Subscription {
return this.itemService
.getItems()
.subscribe(items => this.items = items);
}

refresh(refresher): void {
this.getItems()
.subscribe(() => refresher.complete());
}


And of course, I get a compilation error:
Property 'subscribe' does not exist on type 'Subscription'
, any help on how to achieve this with Observables (RxJS)?

Answer

A Subscription is a listener, you can't listen to a listener, can you?

Instead, you need to return an Observable to be able to subscribe to. Change your function to be as follow (not tested):

getItems(): Observable<any> {
  let obs = this.itemService.getItems().share();
  obs.subscribe(items => this.items = items);
  return obs;
}
Comments