gpt4 book ai didi

rxjs - 过滤 BehaviorSubject

转载 作者:行者123 更新时间:2023-12-03 21:19:44 28 4
gpt4 key购买 nike

我有一个 BehaviorSubject我希望能够filter ,但要保持新订阅者在订阅时始终获得一个值的行为主题式质量,即使最后发出的值被过滤掉。有没有一种简洁的方法可以使用 rxjs 的内置函数来做到这一点?例如:

const isEven = (n) => n % 2 === 0;
const source = new BehaviorSubject(1);
const stream = source.pipe(filter(isEven));
stream.subscribe((n) => console.log(n)); // <- I want this to print `1`
source.next(2); // prints `2`; that's good
source.next(3); // does not print anything; that's good

我已经编写了自己的实现,但如果它很容易,我更喜欢使用现有运算符的更简单的解决方案。

最佳答案

只需使用第二个 BehaviorSubject

const { BehaviorSubject } = rxjs;
const { filter} = rxjs.operators;

const isEven = (n) => n % 2 === 0;
const source = new BehaviorSubject(1);
const stream = new BehaviorSubject(source.getValue());

source.pipe(filter(isEven)).subscribe(stream);

stream.subscribe(val => { console.log(val); });
source.next(2);
source.next(3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

关于rxjs - 过滤 BehaviorSubject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526731/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com