Manage Angular component subscriptions using the takeUntil operator

In Rxjs, you can use takeUntil to control the generation of another Observable object data. Using takeUntil, the upstream data is directly transferred to the downstream until the parameter of takeUntil spits out a data or ends.

Just like a faucet switch, it is opened at the beginning, and the upstream data flows directly to the downstream at the beginning. As long as takeUntil is triggered to spit out the data, the faucet is immediately closed.

Taking advantage of this, you can add takeUntil to the pipeline when subscribing, and spit out data when the component is destroyed, so that these subscriptions will be closed immediately, and the memory will be recovered.

Before the transformation:

export class ExampleComponent implements OnInit, OnDestroy {
  subscription1: Subscription;
  subscription2: Subscription;

  ngOnInit(): void {
    this.subscription1 = observable1.subscribe(...);
    this.subscription2 = observable2.subscribe(...);
  }

  ngOnDestroy() {
    this.subscription1.unsubscribe();
    this.subscription2.unsubscribe();
  }
}

After the transformation:

export class ExampleComponent implements OnInit, OnDestroy {
  destroy$: Subject<boolean> = new Subject<boolean>();

  ngOnInit(): void {
    observable1
      .pipe(takeUntil(this.destroy$))
      .subscribe(...);
    observable2
      .pipe(takeUntil(this.destroy$))
      .subscribe(...);
  }

  ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.complete();
  }
}

It is worth noting that takeUntil must be the last operator in the pipe to prevent other operators in the pipe from generating new streams and causing failure.

Summarize

In contrast, you will find that the takeUntil operator is much clearer and more concise. You only need to takeUntil(this.destroy$)add it to the pipeline that stops subscribing when you want the component to be destroyed, and you can manage it uniformly.

Guess you like

Origin blog.csdn.net/qq_38679823/article/details/132365315