Reset ReplaySubject value

527 views Asked by At

I have such file structure:

  • facade.ts
  • state.ts
  • component.ts

In facade I have:

...
getArticles(): Observable<Article> {
  return this.articleService.fetchAll();
}
...

In state I have:

...
triggerArticlesFetch$ = new ReplaySubject<void>(1);

articles$ = this.triggerArticlesFetch$.pipe(
  switchMap(() => this.fc.getArticles()),
  shareReplay(1)
);

loadArticles(): void {
  this.triggerArticlesFetch$.next();
}

getArticles(): Observable<ArticleShare[]> {
  return this.articles$;
}
...

and finally in component I have:

...
`
  <span> {{ articles$ | async | json }} </span>
`
...
...
articles$: Observable<Article> = this.st.getArticles();

ngOnInit() {
  this.st.loadArticles();
}
...

But I have some issues with 'invalidating' this data (component is reusable - and state contains previous data).

What is the best way to clear/reset to []/null articles$ (probably in state file) everytime I call loadArticles() ?

1

There are 1 answers

1
Michael D On BEST ANSWER

Expanding from my comment (and as I understand) the observable should start with [] (or null) each time a component is initialized. The quickest fix I could think of is to pipe in a startWith to the source.

Try the following

state

...
triggerArticlesFetch$ = new ReplaySubject<void>(1);

articles$ = this.triggerArticlesFetch$.pipe(
  switchMap(() => 
    this.fc.getArticles().pipe(
      startWith([]) // or `null` as per requirement
    )
  ),
  shareReplay(1)
);