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.
j
Jonathan
10/05/2018, 12:13 PM
You should avoid returning
Job
or
Deferred
and make funciton suspend or extension of
CoroutineScope
.
Jonathan
10/05/2018, 12:13 PM
Copy code
suspend 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 PM
A suspending function which returns a deferred is actually very strange. It basically means promising the future of a value... Always remember that a suspending function is the exact equivalent of a function returning a promise 😉
a
Albert
10/05/2018, 12:20 PM
thanks@Jonathan. that makes sense. I tend to compare it with C# time to time, which I shouldn't do
s
streetsofboston
10/05/2018, 2:14 PM
@Albert Yes, try to avoid using `Deferred`s and use “plain”
suspend
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.