CoroutineScope.cancel() extension to reduce boiler-plate in a typical UI app
See original GitHub issueI’m reading Android codelabs on coroutines here https://codelabs.developers.google.com/codelabs/kotlin-coroutines/index.html#4
It gave me a fresh look on the pattern we are advertising for CoroutineScope
. There it is being cast without inheritance:
private val viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
This does look like bit a boilerplate, even if you have to write it once in your app. What we can do, is to have a cancel()
extension function directly on CoroutineScope
.
PRO: It is going to simplify the above code (note that CoroutineScope(...)
constructor always creates a Job
object):
private val uiScope = CoroutineScope(Dispatchers.Main)
override fun onCleared() {
super.onCleared()
uiScope.cancel()
}
CON: We have a convention of declaring “coroutine builder” functions as extensions on CoroutineScope
. It mean, that if we have cancel()
extension on CoroutineScope
, then it will become available as cancel()
in the scope of those coroutine builder functions, which could be confusing and is completely useless (at least, I don’t see a use-case for cancel()
in the scope of coroutine builder). I don’t have a nice solution for this downside.
Any comments?
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (8 by maintainers)
Top GitHub Comments
@objcode
CancellableCoroutineScope
can be an inline class, indeed. However, it kind of misnomer, since every instance ofCoroutineScope
should be cancellable, since we already have code to create aJob()
in a regularCoroutineScope(...)
constructor function.I’ve looked at the usage via
coroutineContext
that you’ve proposed and it already seems quite good for me. Maybe we shall just update codelab to use this pattern and stop trying to further improve it:LGTM. I’ll close this issue.