什么时候应该使用blockingGet? [英] When should I use blockingGet?
问题描述
我在工作中经常使用 RxJava,并看到了一些调用方法的示例,该方法返回 Observable 或 Single,然后在其上调用 BlockingGet 以在不同的 .我在想这可能是对图书馆和概念的误用,但我可能是错的.我举个小例子:
I am using RxJava a lot for work and seen some examples of calling a method which returns an Observable or Single and then calling blockingGet on it to use the results in a different . I was thinking this might be a misuse of the library and the concept but I might be wrong. I will give a small example:
public Observable<String> getStrings(){
// return sg
}
public Observable<String> getNames(){
// return names
}
public Observable<String> filterNamesInStrings() {
List<String> names = getNames().toList().blockingGet();
return getStrings().filter(str -> /*is str in names list*/)
}
filterNamesInStrings
也可以通过以下方式解决:
The filterNamesInStrings
could also be solved by:
getNames()
.toList()
.flatMapObservable(names->
getStrings().filter(str -> /*is str in names list*/)
我的直觉是第二个解决方案更好,但我唯一的原因是我觉得使用 blocksGet 我们有点打破了可观察的链,失去了懒惰(我不确定 Rx 有多懒惰)但是我没有找到任何可以证明我的观点的东西也没有什么可以进一步说明第二个更好的.另外,如果我是对的,除了快速测试之外,我没有看到任何其他用于阻止 get 的用例,这是真的吗?
My intuition is that the second solution is better, but the only reason I have is that I feel with using blockingGet we kind of break the chain of observables, lose the laziness (I'm not sure tho how lazy Rx is) but I did not find anything to prove my points also nothing to further explain that the second is better. Also if I am right I don't see any other use case for blocking get than quick testing, is that true?
我的问题:
- 我的问题是有效的还是实现之间的差异可以忽略不计?
- 是否有任何解决方案比其他解决方案更好/更适用于库?如果是,为什么以及是否有使用 blocksGet 的正当理由?
- (可选:你能给我推荐一本关于理解 ReactiveX 深度的好书吗,这样我就能得到关于此类问题的解释,而且良好实践"列表/书会很方便)
推荐答案
我的问题是有效的还是实现之间的差异可以忽略不计?
Is my question a valid one or the difference is negligible between the implementations?
blockingGet
阻塞当前线程,因此您几乎肯定不想在测试之外调用它.第二个例子是正确的方法.
blockingGet
blocks the current thread, so you almost certainly don't want to call it outside of tests. The second example is the right approach.
是否有任何解决方案比其他解决方案更好/更适合库,如果是这样,为什么以及是否有正当理由使用 blocksGet 呢?
Is any of the solutions better/more true to the library than the other, if so why and is there a valid reason to use blockingGet then?
主要是测试.或者很少,当使用完全同步的代码时,实际上不会发生阻塞.
Tests mainly. Or rarely, when working with fully synchronous code where blocking never actually happens.
了解 ReactiveX 的深度
understanding the depths of ReactiveX
没有适合这种深度的书.所有关于 RxJava 的书籍都适合阅读.
There is no book for this depth. All books about RxJava are fine to read.
这篇关于什么时候应该使用blockingGet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!