takeUntil之后执行一些操作

时间:2018-10-19 05:23:04

标签: rxjs

我正在监听mousemove事件,直到mouseup。我正在使用takeUntil

我的代码:

    const onMouseMove = fromEvent(window, "mousemove");
    const onMouseUp = fromEvent(window, "mouseup");

    const resizePanel = onMouseMove
        .pipe(
            takeUntil(onMouseUp),
            map(
                (event: MouseEvent) => {
                    this.isDragging = true;
                    this.resizePanel(event.clientX);
                }
            )
        );

我有一个变量isDragging: boolean,我想在发生false时将其设置为mouseup,例如在我的代码中takeUntil之后。它必须很简单,但我无法弄清楚。

3 个答案:

答案 0 :(得分:0)

您需要订阅

const { fromEvent } = rxjs;

const onMouseUp$ = fromEvent(document, "mouseup");

onMouseUp$.subscribe(onMouseUp => {
  console.log('mouse up');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script>

takeUntil结束可观察的结果,在takeUntil之后什么也没发生。

答案 1 :(得分:0)

您可以在onMouseMove $和onMouseUp $上使用CombineLatest,并在takeUntil中使用finalize主题。

const { fromEvent, combineLatest, Subject } = rxjs;
const { takeUntil } = rxjs.operators;

const onMouseMove$ = fromEvent(window, "mousemove");
const onMouseUp$ = fromEvent(document, "mouseup");

const finalise = new Subject();

combineLatest(onMouseMove$, onMouseUp$).pipe(takeUntil(finalise)).subscribe(([onMouseMove, onMouseUp]) => {
  if (onMouseUp) {
    console.log('mouse up');
    finalise.next(true);
    finalise.complete();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script>

答案 2 :(得分:0)

您可能想尝试类似的东西

const onMouseMove = fromEvent(window, "mousemove");
const onMouseUp = fromEvent(window, "mouseup");

const resizePanel = onMouseMove
    .pipe(
        takeUntil(onMouseUp.pipe(tap(() => this.isDragging = false))),
        map(
            (event: MouseEvent) => {
                this.isDragging = true;
                this.resizePanel(event.clientX);
            }
        )
    );

这个想法是将pipe的{​​{1}}运算符添加到tap用作onMouseUp的参数