Ashwin Kumar Ashwin Kumar - 3 months ago 34
Javascript Question

Using Rx.Observable from event with pausable does not run the subscribe function

Note: I am using typescript with rxjs(2.5.3) here

I am trying to determine idle click times on a screen for 5 seconds

var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, 'click')
.bufferWithTime(5000)
.filter(eventBundle => {
return eventBundle.length === 0;
});


This is the subscribe function

var noClickStreamSubscriber = noClickStream.subscribeOnNext(() => {
this.showLogoutWarning = true;
});


This runs the code fine. The subscriber gets called when there is no click for 5 seconds.

Now, I actually want to be able to pause and resume the noClickStream in the subscribe function when the warning screen is being shown. For this I added pausable() to the initial no click stream.

var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, 'click')
.bufferWithTime(5000)
.filter(eventBundle => {
return eventBundle.length === 0;
})
.pausable();


Now the noClickStreamSubscriber function never gets called even after 5 seconds of no click activity. Does fromEvent not support pausable functionality?

Answer

The reason for the subscribe function not executing when the observable is declared as pausable is that the event stream starts in paused state. To get the stream to work, after the subscribe function is defined, noClickStream.resume() must be invoked.

var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, 'click')
            .bufferWithTime(5000)
            .filter(eventBundle => {
                return eventBundle.length === 0;
            })
            .pausable();

var noClickStreamSubscriber = noClickStream.subscribeOnNext(() => {                                   
                this.showLogoutWarning = true;
});

noClickStream.resume(); // This has to be invoked
Comments