Home > Net >  I can't find the Dispathcers.IO in the coroutine
I can't find the Dispathcers.IO in the coroutine

Time:10-04

i'm studying android by a book. according to the book, i need to create a repository to get data from the network response. and i had create a livedata to store info. here are the codes on my book.

object Repository {

    fun searchPlaces(query: String) = liveData(Dispatchers.IO) {
        val result = try {
            val placeResponse = SunnyWeatherNetwork.searchPlaces(query)
            if (placeResponse.status == "ok") {
                val places = placeResponse.places
                Result.success(places)
            } else {
                Result.failure(RuntimeException("response status is ${placeResponse.status}"))
            }
        } catch (e: Exception) {
            Result.failure<Place>(e)
        }
        emit(result)
    }

But when I copied the codes, i found that the second row's Dispatchers.IO was wrong. and i tried to import the kotlinx.coroutines.Dispatchers, the IDE can't find it. finally i abandoned the codes, and the app run successfully. i can't understand the specific principles

this is my build.gradle.

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"

and how can i use the Dispatchers.IO?

CodePudding user response:

In order to use Dispatchers.IO you should add Kotlin Coroutines dependency. You can find it here. More info about Coroutines Dispatchers you can find here.

The coroutine context includes a coroutine dispatcher (see CoroutineDispatcher) that determines what thread or threads the corresponding coroutine uses for its execution. The coroutine dispatcher can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined.

CodePudding user response:

Dispatchers.IO belongs to kotlinx-coroutines-core package.

Add kotlinx-coroutines-core implementation to your module's build.gradle

dependencies{
      def coroutinesVersion = '1.5.2-native-mt'
      implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
}
  • Related