I am new to Kotlin for Android development, and I was wondering which of the following approaches is recommended when working with Coroutine?
In this approach, each function will overwrite the caller context to the appropriate one.
My Assumption: The benefit is that the caller function doesn't need to know about the inners of the function it calls.
suspend fun callee() = withContext(Dispatchers.IO) {
httpClient.get("https://google.com")
}
suspend fun caller() {
callee()
callee()
}
Here, we leave the decision to the caller function, meaning it can pick any context appropriate for that use case.
Please Challenge: This lowers the code complexity and the overhead of context switching.
suspend fun callee() {
httpClient.get("https://google.com")
}
suspend fun caller() {
// Specify context only once
withContext(Dispatchers.Main) {
callee()
callee()
}
}
Since I use KTOR client, can I assume that the library already picks the correct context and I don't need to specify them?
suspend fun callee() {
// Assumption: Ktor will run the request in correct context
httpClient.get("https://google.com")
}
suspend fun caller() {
callee()
callee()
}
If you see a suspend function which blocks the thread or expects to be called in a specific thread, then this function was implemented incorrectly.
Of course, we can sometimes ignore such rules when implementing an internal, private functionality inside a class. Maybe we would like to e.g. split a bigger block of code performing I/O into multiple smaller functions, but we still need them to be suspendable. In that case it probably makes sense to switch to Dispatchers.IO
only once, at the entry point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With