简体   繁体   中英

Kotlin coroutine with no suspend functions

So I have to make a network call and for that I am using coroutines like this:

lifecycleScope.launch {
    sendData()
}

private suspend fun sendData() = withContext(Dispatchers.IO) {
    try {
        withTimeout(5000L) {
           // Sends a network request and handles response using a network function without suspend
        }
    } catch(e: TimeoutCancellationException) {
        ...
    }
}

My question is, does this have drawbacks over creating a Runnable? Since there are no suspend functions called from within sendData() and the network function called from this function is a regular blocking call. Is it bad practice to use coroutines here?

No, it is not a bad practice.

I can see that you are creating a suspend function because you want to change thread and specify timeout for the network call.

It is not a must to call suspend function inside another suspend function .

But, suspend function can only be called inside Coroutine Builder or another suspend function .

Thanks to Marko Topolnik for the details :)

If the HTTP request dependency you are using includes a callback, then the library by itself is taking care of threading. Retrofit does that.

So the HTTP request will be none blocking, but the callback will be in the main thread, making unnecessary the suspend.

Similarly, if there is a callback, then a runnable is not needed either.

Please be aware that coroutines and threads are not the same, tend to be related, but not all the coroutines are background thread.

The drawback is what you do after the HTTP request in the callback. Generally, the HTTP request is followed by writing on the DB, so that is why dependencies that provide callbacks, are still wrapped in abstraction and use the blocking method provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM