androidkotlinrx-javakotlin-coroutinesrx-java2

Fire and forget coroutine job


Here is a the actual code in Rxjava. Its a fire and forget database operation

 fun saveResponseToDb() {
    Observable.just(database)
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.io())
        .subscribe({ dataBase: DataBase ->
            dataBase.doSomething()
        }, { t: Throwable? -> printStackTrace(t) })
}

What is the Coroutine Equivalent of the same?

I have added a sample equivalent code

 val scope = CoroutineScope(Dispatchers.IO)
    scope.launch {
        dataBase.doSomething()
        scope.cancel()
    }



val job = Job()
    val scope = CoroutineScope(job + Dispatchers.IO)
    scope.launch {
        dataBase.doSomething()
        job.complete()
    }

Is it necessary to cancel the scope or call complete? Which is the right way to do it? What happens when you call or do not call the scope cancel or job complete?

What is the right way to do a fire and forget call in Kotlin-Coroutines?


Solution

  • If you really like to run a fire and forget job, and you understand all problems associated with this, then you can use the GlobalScope:

    GlobalScope.launch(Dispatchers.IO) {
        dataBase.doSomething()
    }
    

    Creating a single-use CoroutineScope which you don't store anywhere, is just a more convoluted way to do the same as using the GlobalScope.

    However, if you don't wait for the operation to finish, you don't read its results, you don't observe it for failures, you never cancel it, you don't switch between IO/CPU/UI workloads, you don't fork the task into multiple concurrent subtasks, etc., then you pretty much opted-out from all coroutines features already. At this point the above code is not much different than simply starting a background thread:

    thread {
        dataBase.doSomething()
    }
    

    Maybe the only difference is that coroutines provide a global, shared thread pool. I'm not very familiar with RxJava, but I suspect it is the same in your original code. You don't really use RxJava framework, you use it merely as a provider of a global thread pool.