如果有一个为真,我如何将 2 个布尔 observable 组合成一个布尔 observable? [英] How do I combine 2 boolean observables into a single boolean observable if either are true?

查看:44
本文介绍了如果有一个为真,我如何将 2 个布尔 observable 组合成一个布尔 observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使我的特定条件尽可能简单,我有以下观察值.

To make my specific condition as easy as possible I have the following observables.

const a = of(true);
const b = of(true);

我希望确定如果这些中的一个或两个都为真,则返回可观察到的真,但如果两者都为假,则返回可观察到的假.

I am looking to determine that if either or both of these are true then return an observable of true but if both are false, return an observable of false.

if (a || b) ? true : false;

我似乎对如何正确组合它们感到困惑,我使用 combineLatest 来获取数组.

I seem to be tripping over how to combine them correctly, I was using combineLatest to get an array.

combineLatest([
    a,
    b,
])

// [true, true]

我认为 https://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/some.html 是我所需要的,但这似乎早已不复存在并且正在寻找一些"并不神奇.

I think that https://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/some.html is what I need but that seems long gone and searching for "some" isn't amazing.

combineLatest([
    a,
    b,
]).pipe(
   some(x => x === true)
)

推荐答案

您可以使用 combineLatest 生成基于多个源 observable 的单个 observable:

You can use combineLatest to produce single observable based on multiple source observables:

const myBool$ = combineLatest([a$, b$]).pipe(
    map(([a, b]) => a || b)
);

你的组合 observable 将在任何一个源发出时发出一个值数组(注意它不会第一次发出,直到每个源至少发出一次).然后,您可以使用 map 运算符将发出的数组转换为您的单个布尔值.

Your combined observable will emit an array of values whenever any of the sources emit (note it won't emit for the first time until each source emits at least once). You can then use the map operator to transform the emitted array into your single boolean.

每当任何源发出时,上面的代码都会发出布尔值.但是,如果结果值没有变化,接收发射可能是不可取的(例如:如果 a 和 b 都是 true,则 b 更改为 false,结果还是true).

The code above will emit the boolean value whenever any source emits. However, it may not be desirable to receive emissions if the resultant value hasn't changes (ex: if a and b are both true, then b changes to false, the result is still true).

我们可以通过使用 distinctUntilChanged:

We can prevent emitting the same result by using distinctUntilChanged:

const myBool$ = combineLatest([a$, b$]).pipe(
    map(([a, b]) => a || b),
    distinctUntilChanged()
);

这篇关于如果有一个为真,我如何将 2 个布尔 observable 组合成一个布尔 observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆