Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of observeOn and subscribeOn in Kotlin coroutines

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?

like image 852
Mahdi-Malv Avatar asked Feb 25 '19 07:02

Mahdi-Malv


1 Answers

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
}
like image 194
Choim Avatar answered Sep 28 '22 01:09

Choim