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
insteadbdawg.io
11/27/2018, 3:12 AMval 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 AMgildor
11/27/2018, 3:26 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 PMasad.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 PMasad.awadia
11/27/2018, 1:52 PMasad.awadia
11/27/2018, 1:54 PMasad.awadia
11/27/2018, 1:54 PMasad.awadia
11/27/2018, 1:54 PMasad.awadia
11/27/2018, 1:57 PMasad.awadia
11/27/2018, 1:57 PMlouiscad
11/27/2018, 2:00 PMfun main() = runBlocking(Dispatchers.Default) { … }
louiscad
11/27/2018, 2:01 PMfun main()
needs to return Unit
, be it suspend
or notasad.awadia
11/27/2018, 2:06 PMasad.awadia
11/27/2018, 2:06 PMasad.awadia
11/27/2018, 2:07 PMlouiscad
11/27/2018, 2:09 PMreturn@something
?asad.awadia
11/27/2018, 2:13 PMasad.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 codegildor
11/27/2018, 4:17 PMasad.awadia
11/27/2018, 4:18 PMasad.awadia
11/27/2018, 4:18 PMgildor
11/27/2018, 4:19 PMgildor
11/27/2018, 4:19 PMgildor
11/27/2018, 4:22 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 PMasad.awadia
11/27/2018, 4:24 PMasad.awadia
11/27/2018, 4:24 PMlouiscad
11/27/2018, 6:08 PMcoroutineScope { … }
in suspend fun main()