8
votes

I'm learning Coroutines of Kotlin.

The following content is from the artical https://developer.android.com/kotlin/coroutines.

Important: Using suspend doesn't tell Kotlin to run a function on a background thread. It's normal for suspend functions to operate on the main thread. It's also common to launch coroutines on the main thread. You should always use withContext() inside a suspend function when you need main-safety, such as when reading from or writing to disk, performing network operations, or running CPU-intensive operations.

Normally it's spend long time when I pull data from a remote server, so I need to place "the pull data function" in background thread in order not to freeze main UI.

Should I always add withContext(Dispatchers.IO) in suspend when I use suspend to pull data from remote server?

BTW,

The Code A is from the project https://github.com/googlecodelabs/kotlin-coroutines, you can see it .

But I can't find the keyword withContext() in the project, why?

Code A

fun refreshTitle() = launchDataLoad {
    repository.refreshTitle()
}


private fun launchDataLoad(block: suspend () -> Unit): Unit {
    viewModelScope.launch {
        try {
            _spinner.value = true
            block()
        } catch (error: TitleRefreshError) {
            _snackBar.value = error.message
        } finally {
            _spinner.value = false
        }
    }
}
1
Don't use withContext() to call suspendable functions. They are main-safe. - Marko Topolnik

1 Answers

8
votes

Should I always add withContext(Dispatchers.IO) in suspend when I use suspend to pull data from remote server?

It depends. If the you use a library like Retrofit 2.6.0 that has native support for suspend, the dispatcher is already Dispatchers.IO (or whatever the library deems more appropriate).

If the call to pull data from a remote server is blocking, you need to make sure to run it on Dispatcher.IO yourself with withContext(Dispatchers.IO) to not block the main thread.

I can't find the keyword withContext() in the project, why?

Because the project uses Retrofit, so the switch to Dispatchers.IO happens under the hood: https://github.com/googlecodelabs/kotlin-coroutines/blob/master/coroutines-codelab/finished_code/src/main/java/com/example/android/kotlincoroutines/main/MainNetwork.kt