Albert
10/05/2018, 12:09 PMcurrentScope is deprecated. For example:
suspend fun httpGetAsync(): Deferred<String> = currentScope {
async {
// ... Do HTTP GET
}
}
suspend fun main() {
coroutineScope {
val request1 = httpGetAsync()
val request2 = httpGetAsync()
println("${request1.await()} - ${request2.await()")
}
}
If httpGetAsync was using coroutineScope, it means that request2 will be filled when request1 is completely done.Jonathan
10/05/2018, 12:13 PMJob or Deferred and make funciton suspend or extension of CoroutineScope.Jonathan
10/05/2018, 12:13 PMsuspend fun httpGet(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
// ... Do HTTP GET
"result"
}
suspend fun main() {
coroutineScope {
val request1 = async { httpGet() }
val request2 = async { httpGet() }
println("${request1.await()} - ${request2.await()}")
}
}Jonathan
10/05/2018, 12:15 PMAlbert
10/05/2018, 12:20 PMstreetsofboston
10/05/2018, 2:14 PMsuspend function instead. If you really need to handle some special coordination and cancellation between calling and getting the results of `suspend`ed functions, wrap them in an async block, which will return a Deffered, which you then can use to get results or cancel.