https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Martin Devillers

09/17/2018, 1:01 PM
I’m curious about the example in the coroutines guide for structured concurrency on Android :
Copy code
abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope {
    protected lateinit var job: Job
    override val coroutineContext: CoroutineContext 
        get() = job + Dispatchers.Main
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        job = Job()
    }
        
    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    } 
}
https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy It seems to me that this example is needlessly complicated. The following would work just as well.
Copy code
abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope {
    override val coroutineContext: CoroutineContext = Job()

    override fun onDestroy() {
        super.onDestroy()
        coroutineContext[Job]?.cancel()
    }
}
Since
Dispatchers.Main
is the
ContinuationInterceptor
used when none is available in a
CoroutineContext
, this should yield the same result. Is there something I’m missing?
p

Pavel.AZ

09/17/2018, 1:08 PM
may be override val coroutineContext: CoroutineContext = Job() + Dispatchers.Main ?
m

Martin Devillers

09/17/2018, 1:09 PM
That’s kind of my thought as well…
4 Views