Reactive Extensions:如何创建占位符可观察?

时间:2013-07-09 09:43:48

标签: system.reactive reactive-programming reactive-extensions-js

我有一个方法getObs(),它返回一个observable,应由所有调用者共享。但是,当某人调用getObs()并且创建它是异步操作时,该observable可能不存在,所以我的想法是返回一个占位符observable,一旦它被创建就被替换为真实的observable。

我的基本尝试是这样的:

var createSubject = new Rx.Subject();
var placeholder = createSubject.switchLatest();

如果在调用'getObs()'时,如果真正的observable不存在,我可以返回placeholder。创建真正的observable后,我使用createSubject.onNext(realObservable),然后将其传递给switchLatest(),为任何订阅者解包它。

但是,为了这个目的,使用Subject和switchLatest似乎有些过分,所以我想知道是否有更直接的解决方案?

2 个答案:

答案 0 :(得分:2)

如果获取observable本身的行为是异步的,你应该将其建模为可观察的。

例如......

var getObsAsync = function () {
    return Rx.Observable.create(function (observer) {
        var token = startSomeAsyncAction(function (result) {
                // the async action has completed!
                var obs = Rx.Observable.fromArray(result.dataArray);
                token = undefined;
                observer.OnNext(obs);
                observer.OnCompleted();
            }),
            unsubscribeAction = function () {
                if (asyncAction) {
                    stopSomeAsyncAction(token);
                }
            };            

        return unsubscribeAction;
    });
};

var getObs = function () { return getObsAsync().switchLatest(); };

如果您想共享该observable的单个实例,但是您不希望获得可观察的直到某人实际订阅,那么您可以:

// source must be a Connectable Observable (ie the result of Publish or Replay)
// will connect the observable the first time an observer subscribes
// If an action is supplied, then it will call the action with a disposable
// that can be used to disconnect the observable.
// idea taken from Rxx project
Rx.Observable.prototype.prime = function (action) {
    var source = this;
    if (!(source instanceof Rx.Observable) || !source.connect) {
        throw new Error("source must be a connectable observable");
    }

    var connection = undefined;
    return Rx.Observable.createWithDisposable(function (observer) {
        var subscription = source.subscribe(observer);

        if (!connection) {
            // this is the first observer.  Connect the underlying observable.
            connection = source.connect();
            if (action) {
                // Call action with a disposable that will disconnect and reset our state
                var disconnect = function() {
                    connection.dispose();
                    connection = undefined;
                };
                action(Rx.Disposable.create(disconnect));
            }
        }

        return subscription;
    });
};

var globalObs = Rx.Observable.defer(getObs).publish().prime();

现在代码可以只使用globalObs而不用担心:

// location 1
globalObs.subscribe(...);

// location 2
globalObs.select(...)...subscribe(...);

请注意,实际上甚至没有人需要调用getObs,因为您只需设置一个全局可观察对象(通过defer)在有人订阅时为您调用getObs

答案 1 :(得分:1)

您可以在事后使用主题来连接源:

var placeholder = new Subject<YourType>();
// other code can now subscribe to placeholder, best expose it as IObservable

创建源时:

var asyncCreatedObs = new ...;
placeholder.Subscribe(asyncCreatedObs);
// subscribers of placeholder start to see asyncCreatedObs