如果获取 observable 本身的行为是异步的,那么您也应该将其建模为 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 的单个实例,但不希望在有人实际订阅之前获得 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