1
votes

I am trying to subscribe to a BehaviourSubject/ReplaySubject with the angular async pipe. Also i have to use auditTime or debounceTime operator to throw away some values.

Here's an example (i used Angular CLI version 7.3.0 and changed app.component only):

import {Component, OnInit} from '@angular/core';
import {Observable, ReplaySubject, Subject} from 'rxjs';
import {auditTime, tap} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `{{value$ | async}}`,
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {

  private readonly subjectWithState: Subject<number>;

  constructor() {
    this.subjectWithState = new ReplaySubject(1);
  }

  ngOnInit(): void {
    this.subjectWithState.next(42);
  }

  get value$(): Observable<number> {
    return this.subjectWithState.asObservable()
      .pipe(
        tap(value => console.log(value)),
        auditTime(1000),
      );
  }
}

The problem is the subject don't stop emitting the (single) value and i don't get any output (see console logs). Everything works as expected with a simple Subject or without auditTime(1000).

I can't find anything which would explain this behavior. How can i use the auditTime or debounceTime operator with async pipe and BehaviourSubject or ReplaySubject?

1

1 Answers

1
votes

Every time the view accesses value$ a new observable is created. Don't use a getter property and create a property so the same instance of the observable is accessed.

  value$ = this.subjectWithState.asObservable()
    .pipe(
      tap(value => console.log(value)),
      auditTime(1000),
    );