@@ -4,10 +4,7 @@ import androidx.lifecycle.GenericLifecycleObserver
4
4
import androidx.lifecycle.Lifecycle
5
5
import androidx.lifecycle.Lifecycle.State.INITIALIZED
6
6
import androidx.lifecycle.LifecycleOwner
7
- import kotlinx.coroutines.CoroutineScope
8
- import kotlinx.coroutines.Dispatchers
9
- import kotlinx.coroutines.Job
10
- import kotlinx.coroutines.SupervisorJob
7
+ import kotlinx.coroutines.*
11
8
12
9
/* *
13
10
* Returns a [CoroutineScope] that uses [Dispatchers.Main] by default, and that will be cancelled as
@@ -34,14 +31,19 @@ fun Lifecycle.createJob(activeWhile: Lifecycle.State = INITIALIZED): Job {
34
31
" DESTROYED is a terminal state that is forbidden for createJob(…), to avoid leaks."
35
32
}
36
33
return SupervisorJob ().also { job ->
37
- if (! currentState.isAtLeast(activeWhile)) job.cancel()
38
- else addObserver(object : GenericLifecycleObserver {
39
- override fun onStateChanged (source : LifecycleOwner ? , event : Lifecycle .Event ) {
40
- if (! currentState.isAtLeast(activeWhile)) {
41
- removeObserver(this )
42
- job.cancel()
43
- }
34
+ when (currentState) {
35
+ Lifecycle .State .DESTROYED -> job.cancel() // Fast path if already destroyed
36
+ else -> GlobalScope .launch(Dispatchers .Main ) { // State is usually synced on next loop,
37
+ // this allows to use STARTED from onStart in Activities for example.
38
+ addObserver(object : GenericLifecycleObserver {
39
+ override fun onStateChanged (source : LifecycleOwner ? , event : Lifecycle .Event ) {
40
+ if (! currentState.isAtLeast(activeWhile)) {
41
+ removeObserver(this )
42
+ job.cancel()
43
+ }
44
+ }
45
+ })
44
46
}
45
- })
47
+ }
46
48
}
47
49
}
0 commit comments