RxJava:如何在不破坏链条的情况下有条件地将操作符应用于Observable [英] RxJava: How to conditionally apply Operators to an Observable without breaking the chain
问题描述
我在RxJava observable上有一系列运算符。我希望能够根据布尔值应用两个运算符中的一个,而不会破坏链。
I have a chain of operators on an RxJava observable. I'd like to be able to apply one of two operators depending on a boolean value without "breaking the chain".
我对Rx(Java)相对较新而且我觉得这可能比我目前引入临时变量的方法有更多惯用和可读的方法。
I'm relatively new to Rx(Java) and I feel like there's probably a more idiomatic and readable way of doing this than my current approach of introducing a temporary variable.
这是一个具体的例子,从一个可观察的缓冲项目如果批量大小字段为非空,否则使用 toList()
发出单批无限大小:
Here's a concrete example, buffering items from an observable if a batch size field is non-null, otherwise emitting a single batch of unbounded size with toList()
:
Observable<Item> source = Observable.from(newItems);
Observable<List<Item>> batchedSource = batchSize == null ?
source.toList() :
source.buffer(batchSize);
return batchedSource.flatMap(...).map(...)
是这样的事可能吗? (伪lambda因为Java):
Is something like this possible? (pseudo-lambdas because Java):
Observable.from(newItems)
.applyIf(batchSize == null,
{ o.toList() },
{ o.buffer(batchSize) })
.flatMap(...).map(...)
推荐答案
您可以使用撰写(Func1)
保持顺序但是做自定义行为
You can use compose(Func1)
to stay in-sequence but do custom behavior
source
.compose(o -> condition ? o.map(v -> v + 1) : o.map(v -> v * v))
.filter(...)
.subscribe(...)
这篇关于RxJava:如何在不破坏链条的情况下有条件地将操作符应用于Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!