Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29109

How to create Rx observable for some specific non DOM events

I would like to handle some events triggered by a user. And I would like to do that with RxJS Observables.

In my case a user can register a function in the console of the browser like this

window.barfoo.register((bar, foo) => {
    console.log('foo=' + foo + ' bar=' + bar)'
});

Now, to attach the registration to a stream I can wrap the registration code like this

register$ = Rx.Observable.create(observer => {
    window.barfoo.register = (callback) => {
        observer.next(callback);
    };
});

I have my doubts about this code, so I'm wondering if this is the proper way to solve this? The reason for that is, I have to create the function inside the Observable.create callback. Which in my case is a problem. Because window.barfoo.register is created first (and I cannot change that) before I can create the observable.

window.barfoo = {
    register: (cb) => { /* store cb somewhere and trigger something */    
};

register$ = Rx.Observable.create(......????.....); 

Note: although I cannot change the order of things, I can change the implementation of register!

Any suggestions how to setup the observable ?

Upvotes: 1

Views: 134

Answers (1)

martin
martin

Reputation: 96891

RxJS 5 has static constructors to create Observables from different types of events but I think your use-case is different. I was thinking about bindCallback() but that's probably not what you can use if I understand your use-case correctly.

It looks like you'll need to use multicasting for this because otherwise you could override the function multiple times and then only the latest observer will receive any values (note the share() operator at the end).

var register$ = Rx.Observable.create(observer => {
    let oldRegister = window.barfoo.register;
    window.barfoo.register = (callback) => {
        observer.next(callback);
    };

    return () => {
        window.barfoo.register = oldRegister;
    };
}).share();

Also it's probably a good idea to return a teardown function that registers the original function back.

Upvotes: 1

Related Questions