Closed
Description
The Problem
Let's say we have API which expose Single
.
private fun loadData() = Single.fromCallable {
...
}
I want to execute loadData
on background thread and then switch to ui
thread. To do so I have to write write following code, which looks a bit weird (with run
it looks better):
fun main() = launch(UI) {
val result = async(CommonPool) { loadData().await() }.await() // background thread
print(result) // ui thread
}
The Solutions
Add following function to RxAwait
:
public suspend fun <T> SingleSource<T>.await(context: CoroutineContext)
= async(context) { await() }.await()
So the result code would look like this:
fun main() = launch(UI) {
val result = loadData().await(CommonPool) // background thread
print(result) // ui thread
}
Any thoughts on this?
Metadata
Metadata
Assignees
Labels
No labels