欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談Angular 中何時(shí)取消訂閱

 更新時(shí)間:2017年11月22日 10:13:51   作者:semlinker  
本篇文章主要介紹了淺談Angular 中何時(shí)取消訂閱,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

你可能知道當(dāng)你訂閱 Observable 對(duì)象或設(shè)置事件監(jiān)聽(tīng)時(shí),在某個(gè)時(shí)間點(diǎn),你需要執(zhí)行取消訂閱操作,進(jìn)而釋放操作系統(tǒng)的內(nèi)存。否則,你的應(yīng)用程序可能會(huì)出現(xiàn)內(nèi)存泄露。

接下來(lái)讓我們看一下,需要在 ngOnDestroy 生命周期鉤子中,手動(dòng)執(zhí)行取消訂閱操作的一些常見(jiàn)場(chǎng)景。

手動(dòng)釋放資源場(chǎng)景

表單

export class TestComponent {

 ngOnInit() {
  this.form = new FormGroup({...});
  // 監(jiān)聽(tīng)表單值的變化
  this.valueChanges = this.form.valueChanges.subscribe(console.log);
  // 監(jiān)聽(tīng)表單狀態(tài)的變化              
  this.statusChanges = this.form.statusChanges.subscribe(console.log);
 }

 ngOnDestroy() {
  this.valueChanges.unsubscribe();
  this.statusChanges.unsubscribe();
 }
}

以上方案也適用于其它的表單控件。

路由

export class TestComponent {
 constructor(private route: ActivatedRoute, private router: Router) { }

 ngOnInit() {
  this.route.params.subscribe(console.log);
  this.route.queryParams.subscribe(console.log);
  this.route.fragment.subscribe(console.log);
  this.route.data.subscribe(console.log);
  this.route.url.subscribe(console.log);
  
  this.router.events.subscribe(console.log);
 }

 ngOnDestroy() {
  // 手動(dòng)執(zhí)行取消訂閱的操作
 }
}

Renderer 服務(wù)

export class TestComponent {
 constructor(
  private renderer: Renderer2, 
  private element : ElementRef) { }

 ngOnInit() {
  this.click = this.renderer
    .listen(this.element.nativeElement, "click", handler);
 }

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

Infinite Observables

當(dāng)你使用 interval() 或 fromEvent() 操作符時(shí),你創(chuàng)建的是一個(gè)無(wú)限的 Observable 對(duì)象。這樣的話,當(dāng)我們不再需要使用它們的時(shí)候,就需要取消訂閱,手動(dòng)釋放資源。

export class TestComponent {
 constructor(private element : ElementRef) { }

 interval: Subscription;
 click: Subscription;

 ngOnInit() {
  this.interval = Observable.interval(1000).subscribe(console.log);
  this.click = Observable.fromEvent(this.element.nativeElement, 'click')
              .subscribe(console.log);
 }

 ngOnDestroy() {
  this.interval.unsubscribe();
  this.click.unsubscribe();
 }
}

Redux Store

export class TestComponent {

 constructor(private store: Store) { }

 todos: Subscription;

 ngOnInit() {
   /**
   * select(key : string) {
   *  return this.map(state => state[key]).distinctUntilChanged();
   * }
   */
   this.todos = this.store.select('todos').subscribe(console.log); 
 }

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

無(wú)需手動(dòng)釋放資源場(chǎng)景

AsyncPipe

@Component({
 selector: 'test',
 template: `<todos [todos]="todos$ | async"></todos>`
})
export class TestComponent {
 constructor(private store: Store) { }
 
 ngOnInit() {
   this.todos$ = this.store.select('todos');
 }
}

當(dāng)組件銷毀時(shí),async 管道會(huì)自動(dòng)執(zhí)行取消訂閱操作,進(jìn)而避免內(nèi)存泄露的風(fēng)險(xiǎn)。

Angular AsyncPipe 源碼片段

@Pipe({name: 'async', pure: false})
export class AsyncPipe implements OnDestroy, PipeTransform {
 // ...
 constructor(private _ref: ChangeDetectorRef) {}

 ngOnDestroy(): void {
  if (this._subscription) {
   this._dispose();
  }
 }
}

@HostListener

export class TestDirective {
 @HostListener('click')
 onClick() {
  ....
 }
}

需要注意的是,如果使用 @HostListener 裝飾器,添加事件監(jiān)聽(tīng)時(shí),我們無(wú)法手動(dòng)取消訂閱。如果需要手動(dòng)移除事件監(jiān)聽(tīng)的話,可以使用以下的方式:

// subscribe
this.handler = this.renderer.listen('document', "click", event =>{...});

// unsubscribe
this.handler();

Finite Observable

當(dāng)你使用 HTTP 服務(wù)或 timer Observable 對(duì)象時(shí),你也不需要手動(dòng)執(zhí)行取消訂閱操作。

export class TestComponent {
 constructor(private http: Http) { }

 ngOnInit() {
  // 表示1s后發(fā)出值,然后就結(jié)束了
  Observable.timer(1000).subscribe(console.log);
  this.http.get('http://api.com').subscribe(console.log);
 }
}

timer 操作符

操作符簽名

復(fù)制代碼 代碼如下:

public static timer(initialDelay: number | Date, period: number, scheduler: Scheduler): Observable

操作符作用

timer 返回一個(gè)發(fā)出無(wú)限自增數(shù)列的 Observable,具有一定的時(shí)間間隔,這個(gè)間隔由你來(lái)選擇。

操作符示例

// 每隔1秒發(fā)出自增的數(shù)字,3秒后開(kāi)始發(fā)送
var numbers = Rx.Observable.timer(3000, 1000);
numbers.subscribe(x => console.log(x));

// 5秒后發(fā)出一個(gè)數(shù)字
var numbers = Rx.Observable.timer(5000);
numbers.subscribe(x => console.log(x));

最終建議

你應(yīng)該盡可能少的調(diào)用 unsubscribe() 方法,你可以在RxJS: Don't Unsubscribe 這篇文章中了解與 Subject 相關(guān)更多信息。

具體示例如下:

export class TestComponent {
 constructor(private store: Store) { }

 private componetDestroyed: Subject = new Subject();
 todos: Subscription;
 posts: Subscription;

 ngOnInit() {
   this.todos = this.store.select('todos')
           .takeUntil(this.componetDestroyed).subscribe(console.log); 
           
   this.posts = this.store.select('posts')
           .takeUntil(this.componetDestroyed).subscribe(console.log); 
 }

 ngOnDestroy() {
  this.componetDestroyed.next();
  this.componetDestroyed.unsubscribe();
 }
}

takeUntil 操作符

操作符簽名

public takeUntil(notifier: Observable): Observable<T>

操作符作用

發(fā)出源 Observable 發(fā)出的值,直到 notifier Observable 發(fā)出值。

操作符示例

var interval = Rx.Observable.interval(1000);
var clicks = Rx.Observable.fromEvent(document, 'click');
var result = interval.takeUntil(clicks);

result.subscribe(x => console.log(x));

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論