Android-CleanArchitecture-Kotlin
Android-CleanArchitecture-Kotlin copied to clipboard
Asynchronous approach for UseCase execute function
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. 👍 🙇
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?
If you use suspend funinstead then you can rely on the benefits of structured concurrency
@Zhuinden thanks I changed it, but can you please brief on suspend fun on how it is more better?