Return 单发射器 Rx 的值 Java
Return value of Single emitter Rx Java
如何 return 从 Rx 中的 Single observable 获取值 Java
fun fetchRunResult() : Single<Boolean>{
return Single.just(false)
}
fun canRun() : Boolean {
return person.fetchRunResult() // get boolean instead of Single
}
响应式和非响应式世界之间的转换是通过以下方式完成的:阻塞调用或订阅
Why use reactive?
- 在没有回调地狱的情况下编写异步事件流
- 将系统设计为流
Convert Reactive-Type to Non-Reactive-Type: Blocking
fun canRun() : Boolean {
return person.fetchRunResult().blockingGet()
}
使用此方法,您可以只阻塞调用线程,直到值可用为止。
What is the Problem with blocking the calling thread?
- 值可能永远不会到达,因此一个线程永远被阻塞
- 如果被阻塞的线程是一个 ui 循环,你的 UI 将被冻结,因为线程正在 CountDownLatch 上等待阻塞(实现细节)
Should I convert between Reactive and Non-Reactive type?
我建议谨慎使用。您知道源是同步的,或者您现在知道一个值已经可用。因此#blockingGet 不会阻塞调用线程
What are the alternatives, when the source is async?
为您的流建模并在生命周期处理容器中使用#subscribe。例如 Activity 提供生命周期方法。使用订阅时,调用/订阅线程不会被阻塞。每次有新值可用时,您都会收到回调。此处唯一需要注意的是像在 Disposable 中一样清理资源,因为不这样做可能会导致反应类型泄漏。
Summary:
- 如果您的数据是异步的,您的 API 应该反映这一点,而不是在反应性 <-> 非反应性之间切换
- 尽量不要使用 blockingGet,因为这可能会导致线程被永久阻塞
如何 return 从 Rx 中的 Single observable 获取值 Java
fun fetchRunResult() : Single<Boolean>{
return Single.just(false)
}
fun canRun() : Boolean {
return person.fetchRunResult() // get boolean instead of Single
}
响应式和非响应式世界之间的转换是通过以下方式完成的:阻塞调用或订阅
Why use reactive?
- 在没有回调地狱的情况下编写异步事件流
- 将系统设计为流
Convert Reactive-Type to Non-Reactive-Type: Blocking
fun canRun() : Boolean {
return person.fetchRunResult().blockingGet()
}
使用此方法,您可以只阻塞调用线程,直到值可用为止。
What is the Problem with blocking the calling thread?
- 值可能永远不会到达,因此一个线程永远被阻塞
- 如果被阻塞的线程是一个 ui 循环,你的 UI 将被冻结,因为线程正在 CountDownLatch 上等待阻塞(实现细节)
Should I convert between Reactive and Non-Reactive type?
我建议谨慎使用。您知道源是同步的,或者您现在知道一个值已经可用。因此#blockingGet 不会阻塞调用线程
What are the alternatives, when the source is async?
为您的流建模并在生命周期处理容器中使用#subscribe。例如 Activity 提供生命周期方法。使用订阅时,调用/订阅线程不会被阻塞。每次有新值可用时,您都会收到回调。此处唯一需要注意的是像在 Disposable 中一样清理资源,因为不这样做可能会导致反应类型泄漏。
Summary:
- 如果您的数据是异步的,您的 API 应该反映这一点,而不是在反应性 <-> 非反应性之间切换
- 尽量不要使用 blockingGet,因为这可能会导致线程被永久阻塞