Anatoly Strashkevich
Anatoly Strashkevich

Reputation: 1914

Resubscribe to takeUntil/skipUntil

The following code defines behavior i want (it works). Emmition of mousemove event occur only when mouse down.

Rx.Observable.fromEvent(window,"mouseup")
.subscribe( 
  () => {
      if(subscription)
         subscription.dispose();
  }
) 

Rx.Observable.fromEvent(window,"mousedown")
.subscribe(
  () => {
      subscription = Rx.Observable.fromEvent(window,"mousemove")
                     .subscribe(
                       (event) => console.log(event)
                     )
  }
) 

I want to rewrite it using takeUntil/skipUntil operators. But this fails:

let fs =  [
  (e) => console.log(e),
  (err) => console.log(err),
  () => {
      console.log('done')  
      source.subscribe(...fs);
  }
 ];

let getDown = () => Rx.Observable.fromEvent(document,"mousedown");
let getUp = () => Rx.Observable.fromEvent(document,"mouseup");

let source = Rx.Observable.fromEvent(document,"mousemove")
.skipUntil(getDown())
.takeUntil(getUp());

source.subscribe(
   ...fs
)

How i can do this? Thanks!

Upvotes: 1

Views: 1554

Answers (1)

Matt Burnell
Matt Burnell

Reputation: 2796

This problem is generally solved by projecting each element of the trigger stream into the desired source stream and then flattening things out (which is usually achieved using switchMap). In this case, you want to project downs into moves until ups. Something like this:

const source = getDown().switchMap(() => Rx.Observable.fromEvent(document, "mousemove").takeUntil(getUp());

Upvotes: 3

Related Questions