我想我正在尝试做一些简单的事情,但我没有运气解决它。我想创建一个observable,在调用另一个对象的方法时通知其订阅者。我认为RxJS Observable是正确的方法,但我不知道如何创建我的Observable。我没有权限修改handle.ready函数,因为它在DataLib库中。
//Lets say I need to Observe the handle object for when it calls ready().
let handle = DataLib.getDataAsyncronously();
//sometime in the future DataLib will call handle.ready() which means that
//the data is ready.
let myObservable = Rx.Observable.XXXXXX(handle.ready() is called);
myObservable.subscribe(()=>{
//handle.ready() method just got called.
//Do something now that handle.ready() has been called by DataLib.
});
我如何创建myObservable,以便在调用handle.ready()时通知订阅者?
答案 0 :(得分:0)
附加到句柄的唯一方法是handle.ready()似乎替换它。?
通常,库API更像是
DataLib.handleDataAsyncronously(handler);
或具有事件发射器(onReady())的形状,而不是像这样:
let handle = DataLib.getDataAsyncronously();
我将假设您的库确实具有您在此处描述的API,而不是您可能过度简化它的API。
实施仍然很简单。做了一些假设,包括原始的handle.ready()仍然需要被调用,我会写这样的东西:
const originalHandler = handle.ready.bind(handle);
const ready$ = new Rx.Subject();
handle.ready = () => {
originalHandler();
ready$.onNext(true);
}
ready$
.switchMap(Rx.Observable.from(handle.generatedValues)) // I assume this happens?
.subscribe((handleValue) => {
// handle.ready() method just got called.
// Do something now that handle.ready() has been called by DataLib.
// Or work with handleValue
});
如果你的图书馆至少会返回一个事件发射器,你可以做一些漂亮的事情,如:
const ready$ = Rx.Observable.fromEvent(handle, 'ready');