本文介绍了将观察者存储在全局变量中并稍后使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在代码中创建一个 observable 并生成下一个值?由于其他异步事件,我希望能够从代码的不同部分调用 onNext.

How can I create an observable and generate the next value later in the code? I would like to be able to call onNext from different parts of the code as a result of other async events.

这是我尝试过的,但不起作用:

This is what I have tried, which doesn't work:

var Rx = require('rx');

var GlobalObserver;

var source = Rx.Observable.create(observer => {
    GlobalObserver = observer;
});

var subscription = source.subscribe(
    x => console.log('onNext: %s', x),
    e => console.log('onError: %s', e),
    () => console.log('onCompleted')
);

//...later in the code, as a result of another async event:


    GlobalObserver.onNext(someData);
    ...
    GlobalObserver.onNext(someOtherData);

推荐答案

您需要的是某种主题.ReplaySubjectBehaviorSubjectSubject

What you need is a subject of some sort. ReplaySubject, BehaviorSubject, Subject, etc.

创建一个主题,然后您可以执行subject.subscribe(...) 来订阅它.您也可以执行 subject.onNext(...) 添加到流中.

Create a subject, then you can do subject.subscribe(...) to subscribe to it. You can also do subject.onNext(...) to add to the stream.

例如:

var subject = new Rx.Subject();

var subscription = subject.subscribe(
    function (x) { console.log('onNext: ' + x); },
    function (e) { console.log('onError: ' + e.message); },
    function () { console.log('onCompleted'); }
);

subject.onNext(1);
// => onNext: 1

subject.onNext(2);
// => onNext: 2

subject.onCompleted();
// => onCompleted

subscription.dispose();

一个更具体的用例(每次成功的 HTTP 响应返回时都会添加到可观察流中):

A more specific use case (will add to the observable stream every time a successful HTTP response comes back):

var httpResponseStream = new Rx.Subject();

var subscription = httpResponseStream.subscribe(function (response) { 
    console.log('HTTP response success: ', response); 
});

makeAJAXCall().then(function (response) {
    httpResponseStream.onNext(response);
});

正如另一位用户所说,如果您使用的是 V5,请确保将所有 onNext 更改为 next.如果您使用的是 V4,请坚持使用 onNext.

As another user stated, make sure you change all onNext's to next if you are using V5. If you are using V4, stick to onNext.

这篇关于将观察者存储在全局变量中并稍后使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 04:44