bvdb
bvdb

Reputation: 24770

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.

Upvotes: -1

Views: 207

Answers (2)

Picci
Picci

Reputation: 17762

You may want to consider to create an Observable in cases your callback is called repeatedly and you want to notify a stream of events as a result of the callback being called.

Let's consider, as an example, the node readline function, which accepts a callback which gets fired for each line read and a second callback which is called when the file end is reached.

In this case, we can create an Observable which emits for each line read and completes when the end is reached, like in the following example

    function readLineObs(filePath: string) => {
        return new Observable(
            (observer: Observer<string>): TeardownLogic => {
                const rl = readline.createInterface({
                    input: fs.createReadStream(filePath),
                    crlfDelay: Infinity,
                });

                rl.on('line', (line: string) => {
                    observer.next(line);
                });
                rl.on('close', () => {
                    observer.complete();
                });
            },
        );
    };

Upvotes: 0

Fan Cheung
Fan Cheung

Reputation: 11370

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)
})

Upvotes: 1

Related Questions