programing

서브스크립션 배열 대신 SubSink를 사용하는 이유

javajsp 2023. 6. 28. 21:20

서브스크립션 배열 대신 SubSink를 사용하는 이유

저는 존 파파가 서브싱크에 대해 이야기하는 ngConf 비디오를 방금 봤어요. SubSink를 최고의 방법으로 구독을 취소하기 위해서요.

저는 실제로 서브스크립션[]을 사용하고 있었는데, 각 서브스크립션 취소 시 cmp 파괴 시마다 서브스크립션을 푸시합니다.

그들은 제가 놓친 것인가요 아니면 서브싱크를 사용하기 위한 가독성 향상일 뿐인가요?

타사 라이브러리를 설치하지 않고 .add() 메서드를 사용하여 구독을 그룹화하는 방법도 있습니다.

export class CustomerComponent implements OnInit, OnDestroy {
  constructor(
    private dataService: DataService
  ){}

  private subs = new Subscription();

  ngOnInit() {
    this.subs.add(this.dataService.getCustomer().subscribe());
    this.subs.add(this.dataService.getProducts().subscribe());
  }

  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}

이 방법을 채택하면 최소한 한 가지 이점이 있습니다. 즉, 이 코드를 응용프로그램 논리 밖으로 이동하는 것입니다.구독을 취소하는 것은 청소(필수)에 불과하기 때문입니다.이는 앱에서 생성하는 논리와 관련이 없습니다.

그리고 한 걸음 더 나아가면, 당신은 생략할 수 있습니다.ngOnDestroy구성 요소에서 하나의 어댑터를 생성합니다.NgOnDestroy구현하고 모든 논리를 거기에 배치합니다.

import { OnDestroy } from '@angular/core';
import { SubSink } from './sub-sink';

/**
* A class that automatically unsubscribes all observables when 
* the object gets destroyed
*/
export class UnsubscribeOnDestroyAdapter implements OnDestroy {

/**The subscription sink object that stores all subscriptions */
subs = new SubSink();

/**
* The lifecycle hook that unsubscribes all subscriptions 
* when the component / object gets destroyed
*/
ngOnDestroy(): void {
   this.subs.unsubscribe();
}

RxJs 관찰 자료를 자동으로 구독 취소하는 방법

그 외에는 코드 줄이 몇 줄밖에 없는 아주 작은 패키지입니다.공유해 주셔서 감사합니다 :)

언급URL : https://stackoverflow.com/questions/56215837/what-is-the-point-of-using-subsink-instead-of-a-subscriptions-array