Search code examples
rxjsnode-promisify

subjectify methods with callbacks


I often use the promisify method, which converts a method with a callback signature (e.g. fucntion fn(cb) { ... }) to a method which returns a Promise. It can make the source code a lot cleaner and more compact. So far so good.

Slightly different, are methods which have a callback method, but the callback is called multiple times. In that case a Promise cannot do the trick, because a promise can only be executed once.

In theory, those methods could return a Subject. (e.g. a BehaviorSubject) which would then be fired multiple times.

This made me wondering: Is there a subjectify method somewhere, which can do this for me ?

For example: it could be useful when there is a method which parses a big document. To report on its progress, it could use a callback method. But wrapping it in a Subject could be more convenient.


Solution

  • There are some operator that helps you convert callback to observable https://rxjs-dev.firebaseapp.com/api/index/function/fromEventPattern

    but you can quite easily integrate subject to callback like below

    const progress=new Subject()
    myEvent.on('progress', (p)=>{
       progress.next(p)
    })