Search code examples
androidkotlinkotlinx.coroutines

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?


Solution

  • 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
    }