1

Background:

I am trying to write a message service with Rxjs and angular 6. I use a ReplaySubject to keep the sent messages, then subscriber even after message emited can get them. So the message can be cross different angular components.

I successfully implemented these, however, I meet a problem that for every new subscriber will get the all of messages in the ReplaySubject, I want to delete some particular messages in ReplaySubject. or even clear all the ReplaySubject.

Question:

  • How can I delete some item inside a ReplaySubject?

  • If impossible, is there any work around?

  • If impossible nether, is there any way to create a new ReplaySubject, then copy the subscriber to the new ReplaySubject? so all subscriber can still receive messages.

Many thanks.

Lang
  • 943
  • 13
  • 33

2 Answers2

1

There are bunch of Rxjs operators. You probably need some of the transforming or filtering operators. Simple map() could help too.

For ex. you could return replay subject, and use asObservable:

replaySubject.asObservable().filter(i => i > 5 ).subscribe();

Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
  • Thank you for your suggestion. I want to clear the buffer of the replaySubject. I can use filter to do this, but with the time going, the replayBuffer would be super large. – Lang Sep 15 '18 at 19:11
0
private replaySubject$ = new ReplaySubject<any[]>(1);
private array = <any[]>[];
array$ = this.replaySubject$
    .asObservable()
    .pipe(tap((array) => (this.array = array)));

delete(id: number): Observable<void> {
    return this.http.delete(id).pipe(
      tap(() => {
        this.array = this.array.filter((item) => item.id !== id);
        this.replaySubject$.next(this.array);
      })
    );
  }
Tinismo
  • 39
  • 6