Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will I always add withContext(Dispatchers.IO) in suspend when I pull data from a remote server?

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
        }
    }
}
like image 641
HelloCW Avatar asked Mar 29 '20 07:03

HelloCW


1 Answers

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

like image 159
Enselic Avatar answered Sep 28 '22 10:09

Enselic