Repository: arkivanov/Decompose
Pull request #698 (2024-04-23 20:20:21)

Fixed a bug in MergedLifecycle when one of the lifecycles emits asynchronously


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit


- **Refactor**
	- Enhanced lifecycle management to handle states more accurately.

- **Tests**
	- Added new test cases to ensure the reliability of lifecycle state changes.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: summarize review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>Commits</summary>
> Files that changed from the base of the PR and between 4fd26e6bec47bdc8fd3126cecd39b6f957cabfda and f0a2f2e3f87a31b461bd0e82f5faca6593ddb7e8.
> </details>
> 
> 
> <details>
> <summary>Files selected for processing (2)</summary>
> 
> * decompose/src/commonMain/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycle.kt (3 hunks)
> * decompose/src/commonTest/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycleTest.kt (2 hunks)
> 
> </details>
> 
> 
> ```ascii
>  _______________________________________________
> < Don't count your bugs before they're patched. >
>  -----------------------------------------------
>   \
>    \   (\__/)
>        (•ㅅ•)
>        / 　 づ
> ```

<!-- end of auto-generated comment: summarize review in progress by coderabbit.ai --><!-- tips_start -->

---

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

<details>
<summary>Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
	- `I pushed a fix in commit <commit_id>.`
	- `Generate unit testing code for this file.`
	- `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
	- `@coderabbitai generate unit testing code for this file.`
	-	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
	- `@coderabbitai generate interesting stats about this repository and render them as a table.`
	- `@coderabbitai show all the console.log statements in this repository.`
	- `@coderabbitai read src/utils.ts and generate unit testing code.`
	- `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (invoked as PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger a review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai help` to get help.


Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.

### CodeRabbit Configration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Patch:
diff --git a/decompose/src/commonMain/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycle.kt b/decompose/src/commonMain/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycle.kt
index 1e228dea..0f6c613e 100644
--- a/decompose/src/commonMain/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycle.kt
+++ b/decompose/src/commonMain/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycle.kt
@@ -2,6 +2,7 @@ package com.arkivanov.decompose.lifecycle
 
 import com.arkivanov.decompose.InternalDecomposeApi
 import com.arkivanov.essenty.lifecycle.Lifecycle
+import com.arkivanov.essenty.lifecycle.Lifecycle.State
 import com.arkivanov.essenty.lifecycle.LifecycleRegistry
 import com.arkivanov.essenty.lifecycle.create
 import com.arkivanov.essenty.lifecycle.destroy
@@ -21,11 +22,23 @@ class MergedLifecycle private constructor(
     constructor(lifecycle1: Lifecycle, lifecycle2: Lifecycle) : this(LifecycleRegistry(), lifecycle1, lifecycle2)
 
     init {
-        moveTo(minOf(lifecycle1.state, lifecycle2.state))
+        var state1 = if (lifecycle1.state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
+        var state2 = if (lifecycle2.state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
 
-        if ((lifecycle1.state != Lifecycle.State.DESTROYED) && (lifecycle2.state != Lifecycle.State.DESTROYED)) {
-            val observer1 = CallbacksImpl { state -> moveTo(minOf(state, lifecycle2.state)) }
-            val observer2 = CallbacksImpl { state -> moveTo(minOf(state, lifecycle1.state)) }
+        moveTo(minOf(state1, state2))
+
+        if ((state1 != State.DESTROYED) && (state2 != State.DESTROYED)) {
+            val observer1 =
+                CallbacksImpl { state ->
+                    state1 = state
+                    moveTo(minOf(state, state2))
+                }
+
+            val observer2 =
+                CallbacksImpl { state ->
+                    state2 = state
+                    moveTo(minOf(state, state1))
+                }
 
             lifecycle1.subscribe(observer1)
             lifecycle2.subscribe(observer2)
@@ -37,91 +50,91 @@ class MergedLifecycle private constructor(
         }
     }
 
-    private fun moveTo(state: Lifecycle.State) {
+    private fun moveTo(state: State) {
         when (state) {
-            Lifecycle.State.DESTROYED -> moveToDestroyed()
-            Lifecycle.State.INITIALIZED -> Unit
-            Lifecycle.State.CREATED -> moveToCreated()
-            Lifecycle.State.STARTED -> moveToStarted()
-            Lifecycle.State.RESUMED -> moveToResumed()
+            State.DESTROYED -> moveToDestroyed()
+            State.INITIALIZED -> Unit
+            State.CREATED -> moveToCreated()
+            State.STARTED -> moveToStarted()
+            State.RESUMED -> moveToResumed()
         }
     }
 
     private fun moveToDestroyed() {
         when (registry.state) {
-            Lifecycle.State.DESTROYED -> Unit
+            State.DESTROYED -> Unit
 
-            Lifecycle.State.INITIALIZED -> {
+            State.INITIALIZED -> {
                 registry.create()
                 registry.destroy()
             }
 
-            Lifecycle.State.CREATED,
-            Lifecycle.State.STARTED,
-            Lifecycle.State.RESUMED -> registry.destroy()
+            State.CREATED,
+            State.STARTED,
+            State.RESUMED -> registry.destroy()
         }
     }
 
     private fun moveToCreated() {
         when (registry.state) {
-            Lifecycle.State.DESTROYED -> Unit
-            Lifecycle.State.INITIALIZED -> registry.create()
+            State.DESTROYED -> Unit
+            State.INITIALIZED -> registry.create()
 
-            Lifecycle.State.CREATED -> Unit
+            State.CREATED -> Unit
 
-            Lifecycle.State.STARTED,
-            Lifecycle.State.RESUMED -> registry.stop()
+            State.STARTED,
+            State.RESUMED -> registry.stop()
         }
     }
 
     private fun moveToStarted() {
         when (registry.state) {
-            Lifecycle.State.INITIALIZED,
-            Lifecycle.State.CREATED -> registry.start()
+            State.INITIALIZED,
+            State.CREATED -> registry.start()
 
-            Lifecycle.State.RESUMED -> registry.pause()
+            State.RESUMED -> registry.pause()
 
-            Lifecycle.State.DESTROYED,
-            Lifecycle.State.STARTED -> Unit
+            State.DESTROYED,
+            State.STARTED -> Unit
         }
     }
 
     private fun moveToResumed() {
         when (registry.state) {
-            Lifecycle.State.INITIALIZED,
-            Lifecycle.State.CREATED,
-            Lifecycle.State.STARTED -> registry.resume()
+            State.INITIALIZED,
+            State.CREATED,
+            State.STARTED -> registry.resume()
 
-            Lifecycle.State.RESUMED,
-            Lifecycle.State.DESTROYED -> Unit
+            State.RESUMED,
+            State.DESTROYED -> Unit
         }
     }
 
     private class CallbacksImpl(
-        private val onStateChanged: (Lifecycle.State) -> Unit,
+        private val onStateChanged: (State) -> Unit,
     ) : Lifecycle.Callbacks {
         override fun onCreate() {
-            onStateChanged(Lifecycle.State.CREATED)
+            onStateChanged(State.CREATED)
         }
 
         override fun onStart() {
-            onStateChanged(Lifecycle.State.STARTED)
+            onStateChanged(State.STARTED)
         }
 
         override fun onResume() {
-            onStateChanged(Lifecycle.State.RESUMED)
+            onStateChanged(State.RESUMED)
         }
 
         override fun onPause() {
-            onStateChanged(Lifecycle.State.STARTED)
+            onStateChanged(State.STARTED)
         }
 
         override fun onStop() {
-            onStateChanged(Lifecycle.State.CREATED)
+            onStateChanged(State.CREATED)
         }
 
         override fun onDestroy() {
-            onStateChanged(Lifecycle.State.DESTROYED)
+            onStateChanged(State.DESTROYED)
         }
     }
 }


Test patch:
diff --git a/decompose/src/commonTest/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycleTest.kt b/decompose/src/commonTest/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycleTest.kt
index 6e33aff4..3b31abef 100644
--- a/decompose/src/commonTest/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycleTest.kt
+++ b/decompose/src/commonTest/kotlin/com/arkivanov/decompose/lifecycle/MergedLifecycleTest.kt
@@ -408,7 +408,6 @@ class MergedLifecycleTest {
         lifecycle1.create()
         lifecycle1.destroy()
 
-        toString()
         val merged = MergedLifecycle(lifecycle1, lifecycle2)
 
         assertEquals(Lifecycle.State.DESTROYED, merged.state)
@@ -456,9 +455,41 @@ class MergedLifecycleTest {
         lifecycle2.assertNoSubscribers()
     }
 
+    @Test
+    fun GIVEN_lifecycle1_resumed_and_not_emitting_on_subscribe_and_lifecycle2_initialized_WHEN_lifecycle2_and_lifecycle1_resumed_THEN_onCreate_onStart_onResume_called() {
+        val callbacks = TestLifecycleCallbacks()
+        val lifecycle1 = TestLifecycleRegistry(getState = { Lifecycle.State.RESUMED })
+        val merged = MergedLifecycle(lifecycle1, lifecycle2)
+        merged.subscribe(callbacks)
+
+        lifecycle2.resume()
+        lifecycle1.onCreate()
+        lifecycle1.onStart()
+        lifecycle1.onResume()
+
+        callbacks.assertEvents(Event.ON_CREATE, Event.ON_START, Event.ON_RESUME)
+    }
+
+    @Test
+    fun GIVEN_lifecycle2_resumed_and_not_emitting_on_subscribe_and_lifecycle1_initialized_WHEN_lifecycle1_and_lifecycle2_resumed_THEN_onCreate_onStart_onResume_called() {
+        val callbacks = TestLifecycleCallbacks()
+        val lifecycle2 = TestLifecycleRegistry(getState = { Lifecycle.State.RESUMED })
+        val merged = MergedLifecycle(lifecycle1, lifecycle2)
+        merged.subscribe(callbacks)
+
+        lifecycle1.resume()
+        lifecycle2.onCreate()
+        lifecycle2.onStart()
+        lifecycle2.onResume()
+
+        callbacks.assertEvents(Event.ON_CREATE, Event.ON_START, Event.ON_RESUME)
+    }
+
     private class TestLifecycleRegistry(
-        private val registry: LifecycleRegistry = LifecycleRegistry()
+        private val registry: LifecycleRegistry = LifecycleRegistry(),
+        private val getState: () -> Lifecycle.State = registry::state,
     ) : LifecycleRegistry by registry {
+        override val state: Lifecycle.State get() = getState.invoke()
         private val callbacks = HashSet<Lifecycle.Callbacks>()
 
         override fun subscribe(callbacks: Lifecycle.Callbacks) {