@@ -472,26 +472,19 @@ The natural solution to this problem is to associate a [Job] object with each UI
472
472
all the coroutines in the context of this job. But passing associated job object to every coroutine builder is error-prone,
473
473
it is easy to forget it. For this purpose, [ CoroutineScope] interface should be implemented by UI owner, and then every
474
474
coroutine builder defined as an extension on [ CoroutineScope] inherits UI job without explicitly mentioning it.
475
+ For the sake of simplicity, [ MainScope()] factory can be used. It automatically provides ` Dispatchers.Main ` and parent
476
+ job.
475
477
476
478
For example, in Android application an ` Activity ` is initially _ created_ and is _ destroyed_ when it is no longer
477
479
needed and when its memory must be released. A natural solution is to attach an
478
480
instance of a ` Job ` to an instance of an ` Activity ` :
479
481
<!-- - CLEAR -->
480
482
481
483
``` kotlin
482
- abstract class ScopedAppActivity : AppCompatActivity (), CoroutineScope {
483
- protected lateinit var job: Job
484
- override val coroutineContext: CoroutineContext
485
- get() = job + Dispatchers .Main
486
-
487
- override fun onCreate (savedInstanceState : Bundle ? ) {
488
- super .onCreate(savedInstanceState)
489
- job = Job ()
490
- }
491
-
484
+ abstract class ScopedAppActivity : AppCompatActivity (), CoroutineScope by MainScope() {
492
485
override fun onDestroy () {
493
486
super .onDestroy()
494
- job. cancel()
487
+ cancel() // CoroutineScope.cancel
495
488
}
496
489
}
497
490
```
@@ -711,6 +704,7 @@ After delay
711
704
[ Job ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html
712
705
[ Job.cancel ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html
713
706
[ CoroutineScope ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html
707
+ [ MainScope() ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html
714
708
[ coroutineScope ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html
715
709
[ withContext ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html
716
710
[ Dispatchers.Default ] : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html
0 commit comments