How can I complete Observable in RxJS

浪子不回头ぞ 提交于 2019-12-05 18:18:45

问题


Let's say we have an Observable:

var observable = Rx.Observable
    .fromEvent(document.getElementById('emitter'), 'click');

How can I make it Complete (what will trigger onComplete event for all subscribed Observers) ?


回答1:


In this present form, you cannot. Your observable is derived from a source which does not complete so it cannot itself complete. What you can do is extend this source with a completing condition. This would work like :

var end$ = new Rx.Subject();
var observable = Rx.Observable
    .fromEvent(document.getElementById('emitter'), 'click')
    .takeUntil(end$);

When you want to end observable, you do end$.onNext("anything you want here");. That is in the case the ending event is generated by you. If this is another source generating that event (keypress, etc.) then you can directly put an observable derived from that source as an argument of takeUntil.

Documentation:

  • http://reactivex.io/documentation/operators/takeuntil.html
  • https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md



回答2:


What worked for me is using the take() operator. It will fire the complete callback after x number of events. So by passing 1, it will complete after the first event.

Typescript:

private preloadImage(url: string): Observable<Event> {
    let img = new Image();
    let imageSource = Observable.fromEvent(img, "load");

    img.src = url;

    return imageSource.take(1);
}



回答3:


I think what you are looking for is the dispose() method.

from: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables

Notice that the subscribe method returns a Disposable, so that you can unsubscribe to a sequence and dispose of it easily. When you invoke the dispose method on the observable sequence, the observer will stop listening to the observable for data. Normally, you do not need to explicitly call dispose unless you need to unsubscribe early, or when the source observable sequence has a longer life span than the observer. Subscriptions in Rx are designed for fire-and-forget scenarios without the usage of a finalizer. Note that the default behavior of the Observable operators is to dispose of the subscription as soon as possible (i.e, when an onCompleted or onError messages is published). For example, the code will subscribe x to both sequences a and b. If a throws an error, x will immediately be unsubscribed from b.



来源:https://stackoverflow.com/questions/34097158/how-can-i-complete-observable-in-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!