asad.awadia
11/27/2018, 12:49 AMawait
for completion of a suspending function that wraps a blocking call with withContext
bdawg.io
11/27/2018, 3:09 AMwithContext
itself returns the result, so there's no need to await. If you are wanting to execute the withContext
concurrently, use async
insteadval result = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { blockingCall() }
vs val resultAsync = async(<http://Dispatchers.IO|Dispatchers.IO>) { blockingCall() }
doSomethingElse()
val result = resultAsync.await()
asad.awadia
11/27/2018, 3:17 AMgildor
11/27/2018, 3:24 AMfun myApiBlockingCall(): String {
Thread.sleep(1000)
return "Foo"
}
To convert it to non-blocking using withContext:
suspend fun myApiCall() = withContext(IO) {
myApiBlockingCall()
}
And that’s all. You can call myApiCall in any suspend block with any dispatcher without blockingasad.awadia
11/27/2018, 1:06 PMmyApiCall().await()
right - how do I wait for the result?gildor
11/27/2018, 1:17 PMmyApiCall()
asad.awadia
11/27/2018, 1:49 PMlouiscad
11/27/2018, 1:51 PMsuspend fun main()
(new in 1.3) can directly call this suspending functionasad.awadia
11/27/2018, 1:52 PMlouiscad
11/27/2018, 2:00 PMfun main() = runBlocking(Dispatchers.Default) { … }
fun main()
needs to return Unit
, be it suspend
or notasad.awadia
11/27/2018, 2:06 PMlouiscad
11/27/2018, 2:09 PMreturn@something
?asad.awadia
11/27/2018, 2:13 PMlouiscad
11/27/2018, 2:20 PMwithContext
callasad.awadia
11/27/2018, 4:10 PMgildor
11/27/2018, 4:15 PMlaunch
as entry point for your async coroutines codeasad.awadia
11/27/2018, 4:18 PMgildor
11/27/2018, 4:19 PMmain
method is more handy to use fun main() = runBlocking<Unit>{}
instead of suspend fun main() {}
because runBlocking also provides coroutine scopeasad.awadia
11/27/2018, 4:24 PMlouiscad
11/27/2018, 6:08 PMcoroutineScope { … }
in suspend fun main()