Equivalent of observeOn and subscribeOn in Kotlin coroutines

1.8k views Asked by At

For example:

Observable.fromCallable<Int> {
   backgroundTask() // returns an integer
   }
   .observeOn(AndroidSchedulers.mainThread())
   .subscribeOn(Schedulers.io())
   .subscribe ({ number -> /* success */ }, { error -> /* fail */ })

Generally doing a task on the background (another thread) and getting the result of it back in the main thread.

How will this code snippet be using Kotlin coroutines?

1

There are 1 answers

1
Choim On BEST ANSWER

you can switch thread using withContext(). For example,

launch(Dispatchers.MAIN) {
    //main thread here
    val result = withContext(Dispatchers.IO) {
        //IO thread here
        backgroundTask()
    }
    //main thread here again
    //doing something with result
}