Skip to content

Commit 7f063c6

Browse files
committed
Add Lifecycle observer only on next event loop
This allows to support use cases like creating a scope active while STARTED from an Activity onStart() method.
1 parent 8096112 commit 7f063c6

File tree

1 file changed

+14
-12
lines changed
  • integration/kotlinx-coroutines-androidx-lifecycle/src

1 file changed

+14
-12
lines changed

integration/kotlinx-coroutines-androidx-lifecycle/src/Lifecycle.kt

+14-12
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ import androidx.lifecycle.GenericLifecycleObserver
44
import androidx.lifecycle.Lifecycle
55
import androidx.lifecycle.Lifecycle.State.INITIALIZED
66
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.*
118

129
/**
1310
* 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 {
3431
"DESTROYED is a terminal state that is forbidden for createJob(…), to avoid leaks."
3532
}
3633
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+
})
4446
}
45-
})
47+
}
4648
}
4749
}

0 commit comments

Comments
 (0)