user1610458
user1610458

Reputation: 299

Using takeUntil on inner observable

How to write this snippet better?

What I'm trying to achieve is to start a new polling (and discard the previous one) each time eventGenerator$ emits something, but the polling can be discarded also by other notifier (anotherEvent$)

this.eventGenerator.asObservable()
  .subscribe(event => {
    if (this.polling$) {
      this.polling$.unsubscribe();
    }
    this.polling$ = timer(0, 1000)
      .pipe(
        switchMap(() => this.service.getSomething())
        takeUntil(this.anotherEvent$)
      )
      .subscribe();
  })

One of the basic rules is to not subscribe to other subscription inside subscribe() method. For this switchMap operator sounds like a good choice to chain it but if takeUntil is used and the anotherEvent$ emits it will unsubscribe the whole subscription and not only the polling part, so another emit of eventGenerator won't be handled anymore and will not create another timer.

Upvotes: 1

Views: 467

Answers (1)

martin
martin

Reputation: 96891

You can just restructure your operators:

this.eventGenerator$.pipe(
  switchMap(() => timer(0, 1000).pipe(
    switchMap(() => this.service.getSomething()),
    takeUntil(this.anotherEvent$),
  ),
).subscribe(...);

Upvotes: 2

Related Questions