如何在代码后面创建可观察对象并生成下一个值?由于其他异步事件,我希望能够从代码的不同部分调用onNext。
这是我尝试过的,不起作用:
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);
您需要的是某种主题。ReplaySubject,BehaviorSubject,Subject,等。
ReplaySubject
BehaviorSubject
Subject
创建一个主题,然后可以subject.subscribe(...)订阅它。您也subject.onNext(...)可以添加到流中。
subject.subscribe(...)
subject.onNext(...)
例如:
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响应时,都会添加到可观察的流中):
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。
onNext
next