Angular RxJS:在观察订阅或取消订阅时执行某些操作

时间:2017-12-08 10:47:00

标签: javascript angular ionic-framework rxjs observable

我正在使用Javascript app Observables框架中的RxJS将一些Angular个事件翻译为Ionic。我想在“客户端”调用.subscribe()时开始侦听事件,并在调用.unsubscribe()时停止侦听它们。我查看了Observable课程的文档,但我无法看到如何做到这一点。

所以,假设有“onSubscribe”和“onUnsubscribe”方法,我想做这样的事情:

import { Observable, Subject } from 'rxjs';

...

on(name: string) : Observable<Event> {
    let observable = new Subject<any>();

    observable.onSubscribe(() => {
         this.addEventListener(name, (event) => {
             observable.next(event);
         });
    });

    observable.onUnsubscribe(() => {
        this.removeEventListener(name);
    });

    return observable;
}

有没有办法实现这个目标?

谢谢!

1 个答案:

答案 0 :(得分:0)

import { Observable, Subject } from 'rxjs';

...

const unsubscribe;

on(name: string) : Observable<Event> {
    let observable = new Subject<any>();
    // subscribe method returns unsubscribe function, so you have to save in some varibale then call it.
    this.unsubscribe = observable.subscribe(() => {
         this.addEventListener(name, (event) => {
             observable.next(event);
         });
    });

    return observable;
}

// some where else you can do this
unsubscribe();