本文介绍了如何在 RxJS 中完成 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 Observable:

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

我怎样才能让它Complete(什么会为所有订阅的观察者触发onComplete事件)?

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

推荐答案

在目前的形式中,你不能.您的 observable 源自一个不完整的源,因此它本身无法完成.您可以做的是使用完成条件扩展此源.这会像:

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$);

当你想结束 observable 时,你可以执行 end$.onNext("anything you want here");.那就是在结束事件由您生成的情况下.如果这是生成该事件的另一个源(按键等),那么您可以直接将派生自该源的 observable 作为 takeUntil 的参数.

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.

文档:

这篇关于如何在 RxJS 中完成 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:33