Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Storing observer in a global variable and use it later

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

For example:

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...