Best way to use kotlin coroutine scope - android

Viewed 1542

I am new to android & kotlin coroutine. I have been working with okhttp API lib with coroutine. Below is the code:

Application extended Class:

class App: Application() {
    companion object {
        val SCOPE = CoroutineScope(Dispatchers.Main)
    }
}

In MainActivity class:

App.SCOPE.launch {
    val results = Api.get(url)
    UpdateUI(results)
}

Api class:

suspend fun get(url: String): String = withContext(Dispatchers.IO) {
    try {
        val data = httpClient.newCall(request).execute()
        return@withContext data.body!!.string()
    } catch (e: Exception) {
        throw java.lang.Exception(e.message)
    }
}

This is working fine but is this the best way to go?

1 Answers

Please read the medium article regarding operations that shouldn't be canceled. Otherwise, it seems to be correct for the very important operations that need to be executed even when activity and fragment lifecycle gets destroyed. But in your case you are just updating the UI, so does it make sense to still continue the network call or wait for its response when the activity from which you are making the network call gets destroyed? So you should probably use lifecycle coroutine scope as those are scoped to the lifecycle of the component. Please see this android documentation Also, you can use the retrofit to reduce the boilerplate, as retrofit also supports coroutine and you can use suspend modifier in the retrofit ApiInterface and internally retrofit automatically changes the dispatcher to IO(when suspend modifier is used) so you need not do it manually. So your final code would look like this:

In MainActivity class:

lifecycleScope.launch {
    val results = Api.get(url)
    UpdateUI(results)
}

Api class:

suspend fun get(url: String): String = retrofitClient.get(url)
Related