Android-CleanArchitecture-Kotlin icon indicating copy to clipboard operation
Android-CleanArchitecture-Kotlin copied to clipboard

Asynchronous approach for UseCase execute function

Open khairilushan opened this issue 7 years ago • 3 comments

Hi, Currently I found that You do it this way

val job = async(CommonPool) { run(params) }
launch(UI) { onResult.invoke(job.await()) }

Can we just create one coroutine here and just do context switching to execute the UI block code, maybe something like this

launch(CommonPool + job) {
    val result = async(coroutineContext) { run(params) }
    withContext(UI) { onResult.invoke(result.await()) }
}

And the job on this sample is a private property for cancellation purpose.

By the way, thank you so much for always providing us with such an awesome resources. 👍 🙇

khairilushan avatar Jun 05 '18 06:06 khairilushan

 operator fun invoke(params: Params, onResult: (Either<Failure, Type>) -> Unit = {}) {
        val job = GlobalScope.async(/*CommonPool*/ Dispatchers.Default) { run(params) }

        GlobalScope.launch(/*UI*/Dispatchers.Main) { onResult(job.await()) }
    }

I had to change the block of code to this one, I'm wondering on the use of launch,commonpool, etc. Can we still use it in same way or the changed version is ok?

aaghan avatar Apr 27 '20 11:04 aaghan

If you use suspend funinstead then you can rely on the benefits of structured concurrency

Zhuinden avatar Apr 27 '20 13:04 Zhuinden

@Zhuinden thanks I changed it, but can you please brief on suspend fun on how it is more better?

aaghan avatar Apr 28 '20 12:04 aaghan