cartant / eslint-plugin-rxjs-angular

ESLint rules for RxJS and Angular
MIT License
98 stars 11 forks source link

Allow `prefer-takeuntil` to accept `takeUntil` on merged Observable #7

Closed marleau closed 3 years ago

marleau commented 3 years ago

Currently, only a single Subject can be passed to takeUntil. I have a use case where unsubscribe happens on component destruction or on an external signal such as button clicked. To do this, multiple takeUntil's are chained in the pipe. Instead, I'd like to use one takeUntil with a merged Observable (merge(this.onDestroy, this.cancel)).

class FooComponent implements OnDestroy, OnInit {
  private readonly onDestroy = new Subject<void>();
  private readonly cancel = new Subject<void>();

  ngOnInit() {
    fooObservable.pipe(
      takeUntil(merge(this.onDestroy, this.cancel))
    ).subscribe();
  }

  ngOnDestroy() {
    this.onDestroy.next();
    this.onDestroy.complete();
    this.cancel.complete();
  }

  handleCancelButtonClick() {
    this.cancel.next();
  }
}
cartant commented 3 years ago

I don't really have much interest in further complicating this rule. The pattern the rule seeks to enforce is straightforward - a takeUntil is used at the end of the pipeline and it's passed a subject property. If its passed something other than that, it's a pretty significant variation and I don't really have any interest in figuring out where the pattern's subject is if it's passed something else.

An alternative would be to not use the rule for components that don't conform to the pattern or to use multiple takeUntil operators in the pipeline - the rule supports this - placing the ngOnDestroy-related takeUntil last.