简体   繁体   English

如何通过方法创建可观察的rxjs

[英]How to create an rxjs observable from a method

I think I am trying to do something simple but I have had no luck in solving it. 我想我正在尝试做一些简单的事情,但是我没有运气来解决它。 I want to create an observable that notifies its subscribers when the method of another object is called. 我想创建一个可观察对象,该对象在调用另一个对象的方法时通知其订阅者。 I think an RxJS Observable is the right approach but I don't know how to create my Observable. 我认为RxJS Observable是正确的方法,但是我不知道如何创建Observable。 I do not have access to modify the handle.ready function as it is in the DataLib library. 我无权修改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.
});

How would I create myObservable such that subscribers are notified when handle.ready() gets called? 我将如何创建myObservable以便在调用handle.ready()时通知订阅者?

The only way to attach to handle would be to handle.ready() seems to replace it..? 附加到handle的唯一方法是handle.ready()似乎替换了它。

Typically library APIs would be more like this 通常,库API更像这样

DataLib.handleDataAsyncronously(handler);

or have the shape of an event emitter (onReady()) than like this: 或具有事件发射器的形状(onReady()),而不是这样:

let handle = DataLib.getDataAsyncronously();

I will just assume your library does have an API precisely as you have described here rather than you maybe oversimplified it's API. 我只是假设您的库确实具有您在此描述的API,而不是过分简化它的API。

The implementation remains simple. 实现仍然很简单。 Making a number of assumptions, including that the original handle.ready() still needs to be called, I would write something like this: 做出许多假设,包括仍然需要调用原始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
});

If your library would at least return an event emitter, you could do something beautiful like: 如果您的库至少返回一个事件发射器,则可以执行以下类似的操作:

const ready$ = Rx.Observable.fromEvent(handle, 'ready');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM