我正在寻找可以过滤我的可观察对象的现有运算符,如果为真,则可观察对象将完成。
我可以这样做:
obs$.pipe(
filter(value => value),
first()
);
但是我想知道是否有一种方法可以将filter
和first
运算符组合在一起。
我认为skipUntil
是一个不错的选择,但是它会跳过直到发出 observable 为止,直到传递了真实值为止。
答案 0 :(得分:3)
Looks like I had to pay more attention to the docs of first
, which does exactly what I was looking for.
// RxJS v6+
import { from } from 'rxjs';
import { first } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
//emit first item to pass test
const example = source.pipe(first(num => num === 5));
//output: "First to pass test: 5"
const subscribe = example.subscribe(val =>
console.log(`First to pass test: ${val}`)
);
答案 1 :(得分:0)
Use the takeWhile
operator:
const $observableThatCompletes = obs$.takeWhile((value) => true !== value);
The resulting observable will complete as soon as value
is true
.
You can use !value
instead of true !== value
if you want to match all 'truthy' values.