简体   繁体   English

在 RxJava 2 中,如何使一个 Observable 发出另一个 Observable 发出的组合项?

[英]How to Make an Observable that Emits Combined Items Emitted by Another Observable in RxJava 2?

I have an Observable that emits random bits/booleans.我有一个发出随机位/布尔值的 Observable。 I need to make another Observable that combines those random bits to create and emit random integers.我需要制作另一个 Observable 来组合这些随机位来创建和发出随机整数。 Every time the underlying Observable emits a bit, this Observable appends that bit to a bit string, once that bit string reaches a specific length, this Observable converts it to an integer and emits it.每次底层 Observable 发出一个位时,这个 Observable 将该位附加到一个位串,一旦该位串达到特定长度,这个 Observable 将其转换为 integer 并发出。

Here's the illustration:这是插图:插图

Here's how I implement it using Android LiveData:以下是我使用 Android LiveData 实现它的方法:

final StringBuilder bitStringBuilder = new StringBuilder();
final MediatorLiveData<Integer> integerLiveData = new MediatorLiveData<>();
integerLiveData.addSource(
        randomSource.getBooleanLiveData(),
        new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean b) {
                bitStringBuilder.append(b ? '1' : '0');
                if (bitStringBuilder.length() == 31) {
                    integerLiveData.setValue(Integer.parseInt(bitStringBuilder.toString(), 2));
                    bitStringBuilder.setLength(0); // clear the bit string builder
                }
            }
        }
);

How to achieve this using RxJava 2?如何使用 RxJava 2 实现这一点?

Buffer bits:缓冲区位:

source
.buffer(31)
.map(bits -> {
    int result = 0;
    for (int b : bits) {
        result = (result << 1) | (b ? 1 : 0);
    }
    return result;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM