是否有办法从可观察对象中获取第一个和最后一个发出的值?
const down$ = fromEvent(this.canvas, 'mousedown');
const up$ = fromEvent(this.canvas, 'mouseup');
const move$ = fromEvent(this.canvas, 'mousemove');
const drag$ = move$.pipe(
skipUntil(down$),
takeUntil(up$)
);
drag$.subscribe((e: MouseEvent) => {
console.log(e);
});
是否有办法从
drag$观察得到第一个和最后一个值?
答案 0 :(得分:2)
您可以使用take(1)
和takeLast(1)
运算符从Observable中获取第一个和最后一个值。
import { range, merge, Subject } from 'rxjs';
import { take, takeLast, multicast } from 'rxjs/operators';
range(1, 10)
.pipe(
multicast(() => new Subject(), o => merge(
o.pipe(take(1)),
o.pipe(takeLast(1)),
)),
)
.subscribe(v => console.log('result', v));
在您的情况下,您似乎可以执行以下操作,但我不知道您的目标到底是什么:
down$
.pipe(
switchMap(() => move$.pipe(
takeUntil(up$),
multicast(() => new Subject(), o => merge(
o.pipe(take(1)),
o.pipe(takeLast(1)),
)),
)),
)
.subscribe(console.log);
观看现场演示:https://stackblitz.com/edit/rxjs6-demo-ymjoiy?file=index.ts
答案 1 :(得分:0)
对不起,我使事情变得太复杂了。这是我的最终代码:
const up$ = fromEvent(this.canvas, 'mouseup');
const down$ = fromEvent(this.canvas, 'mousedown');
const drag$ = down$.pipe(merge(up$));
drag$.subscribe((e: MouseEvent) => console.log(e); });