reza
reza

Reputation: 6358

Rxjs observable subscriptions never publishing correctly

One of my angular component needs to allow subscriptions to a number that it holds. I am trying to turn this number into an observable so others can subscribe to it.

my publisher looks like

private countChanged = new BehaviorSubject<any>(null);
public historyTimespanChanged$ = this.countChanged.asObservable();

private publish() {
    this.countChanged.next(this.count);
}

expandTimeSpan() {
    this.count ++;
    this.publish();
}

reset() {
    this.count = 0;
    this.publish();
}

getHistoricalCount() {
    return Observable.of(this.count);
}

my observer looks like

        this.historyComponent.getHistoricalCount()
        .subscribe(count => {
            if (count !== 0 ) {
                console.log('new history timespan expanded: ', count);
                this.historyCount = count;
                this.retrieveHistoricalData();
            }
        });

but the subscriber never gets called. Can anyone see what I am doing wrong?

Upvotes: 0

Views: 53

Answers (2)

adz5A
adz5A

Reputation: 2032

Could you share the whole Class of the component ? Because if your subscribe is only called once, with 0 as its value your if clause will never run.

getHistoricalCount() {
     return Observable.of(this.count);
}

Returns an Observable of only one value : v-|, you should try to return the this.historyComponent.countChanged property which is updated by every publish call.

Upvotes: 0

concat
concat

Reputation: 3187

I think that instead of this.historyComponent.getHistoricalCount(), you might've meant this.historyComponent.historyTimespanChanged$.subscribe(...), which derives from the BehaviorSubject that you're publishing to.


On a side note, to avoid the danger and tediousness of appending this.publish to every mutation of count, you may want to look into ReactiveProperty or do it yourself with ES6 setters:

class HistoryComponent {
  ...

  set count(value: number): bool {
    this.countChanged.next(value);
    this.count = value;
    return true;
  }
  ...
}

Upvotes: 1

Related Questions