Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Store#stateFlow(Lifecycle) and Store#labelsChannel(Lifecycle) API, promoted to stable #148

Merged
merged 1 commit into from
Jan 15, 2025

Conversation

arkivanov
Copy link
Owner

@arkivanov arkivanov commented Jan 12, 2025

Summary by CodeRabbit

  • New Features

    • Added lifecycle-aware methods for handling store state flows and label channels
    • Introduced new methods to create state flows and label channels with lifecycle management
  • Documentation

    • Updated method documentation for clarity
    • Removed experimental annotations from existing methods
  • Tests

    • Added new test classes to validate lifecycle and scope-based state flow and label channel behaviors
    • Implemented comprehensive test scenarios for new functionality

Copy link

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request introduces lifecycle-aware extensions for state flows and label channels in the MVIKotlin coroutines library. The changes add new methods to the StoreExtKt class that allow creating state flows and label channels with lifecycle management. These new methods provide a way to automatically handle resource cleanup and subscription management when a lifecycle is destroyed, improving resource management and reducing boilerplate code for developers using the library.

Changes

File Change Summary
mvikotlin-extensions-coroutines/src/commonMain/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StoreExt.kt Added lifecycle-aware stateFlow and labelsChannel methods, removed @ExperimentalMviKotlinApi annotation
mvikotlin-extensions-coroutines/src/commonTest/kotlin/... Added new test classes LabelChannelWithLifecycleTest and StateFlowWithLifecycleTest to validate lifecycle-aware functionality
API files Updated method signatures to include lifecycle-based overloads for stateFlow and labelsChannel

Sequence Diagram

sequenceDiagram
    participant Store
    participant Lifecycle
    participant StateFlow/Channel
    
    Store->>Lifecycle: Observe lifecycle
    Lifecycle-->>Store: Register observer
    Store->>StateFlow/Channel: Emit states/labels
    Lifecycle->>Store: On destroy
    Store->>StateFlow/Channel: Unsubscribe and cleanup
Loading

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Lifecycle Grace

With stores and flows, we dance and weave,
Lifecycle's embrace, we now receive
No more leaks, no memory strain
Cleanup comes with minimal pain
Coroutines hop, with rabbit's might! 🌈


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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 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 for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/LabelChannelWithLifecycleTest.kt (1)

49-53: 🛠️ Refactor suggestion

Duplicate infinite loop pattern

Similar to StateFlowWithLifecycleTest, both test methods use an infinite loop pattern that could be improved.

Also applies to: 68-72

🧹 Nitpick comments (6)
mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithScopeTest.kt (3)

17-33: Consider adding cleanup and testing initial state.

While the test correctly verifies state collection, consider:

  1. Adding scope.cancel() in a finally block to ensure cleanup
  2. Explicitly testing that the initial state (0) is collected first
     @Test
     fun WHEN_state_emitted_THEN_state_collected() {
         val store = TestStore()
         val scope = CoroutineScope(Dispatchers.Unconfined)
         val flow = store.stateFlow(scope)
         val items = ArrayList<Int>()
+        try {
             scope.launch {
                 flow.collect { items += it }
             }
 
             store.stateObserver?.onNext(1)
             store.stateObserver?.onNext(2)
             store.stateObserver?.onNext(3)
 
             assertContentEquals(listOf(0, 1, 2, 3), items)
+        } finally {
+            scope.cancel()
+        }
     }

35-48: Consider testing concurrent state emissions.

The tests cover basic state collection and cleanup, but consider adding a test case for concurrent state emissions to ensure thread-safety.

Would you like me to provide an example test case for concurrent state emissions?


50-77: Add KDoc to document TestStore behavior.

Consider adding documentation to explain:

  • The purpose of this test implementation
  • The behavior of the state observer tracking
  • Why certain methods are no-op
+    /**
+     * Test implementation of [Store] that tracks state observers and provides
+     * controlled state emission for testing purposes.
+     *
+     * @property state Always returns 0 as initial state
+     * @property stateObserver Tracks the current state observer for verification
+     */
     private class TestStore : Store<Int, Int, Int> {
mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithLifecycleTest.kt (1)

22-23: Consider using @BeforeTest for test setup

Both test methods have similar setup code. Consider extracting common setup into a @BeforeTest method to reduce duplication.

+    private lateinit var store: TestStore
+    private lateinit var scope: CoroutineScope
+
+    @BeforeTest
+    fun setUp() {
+        store = TestStore()
+        scope = CoroutineScope(Dispatchers.Unconfined)
+    }

Also applies to: 42-43

mvikotlin-extensions-coroutines/src/commonMain/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StoreExt.kt (2)

46-61: Implementation looks solid with proper lifecycle management!

The implementation correctly:

  • Initializes with current state
  • Updates state through observer
  • Cleans up resources on lifecycle destroy

However, consider documenting the thread-safety guarantees of the StateFlow updates.

Add a note in the documentation about thread-safety:

 * Please note that the actual collection of the [StateFlow] may not be synchronous
 * depending on [CoroutineContext] being used.
+ *
+ * The StateFlow updates are thread-safe and atomic.
 *
 * @param lifecycle a [Lifecycle] used for cancelling the underlying [MutableStateFlow].

138-166: Consider handling channel backpressure more explicitly.

While the implementation correctly manages lifecycle and cleanup, the use of trySend could silently drop labels if the channel is full.

Consider either:

  1. Using send instead of trySend to apply backpressure, or
  2. Adding documentation about potential label drops:
 * Due to the nature of how channels work, it is recommended to have one [Channel] per subscriber.
+ *
+ * Note: Labels might be dropped if the channel is full (when using default BUFFERED capacity).
+ * Consider adjusting the capacity parameter based on your needs.
 *
 * Please note that the actual collection of the [ReceiveChannel] may not be synchronous depending on
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d01538 and bce53e9.

📒 Files selected for processing (8)
  • mvikotlin-extensions-coroutines/api/android/mvikotlin-extensions-coroutines.api (1 hunks)
  • mvikotlin-extensions-coroutines/api/jvm/mvikotlin-extensions-coroutines.api (1 hunks)
  • mvikotlin-extensions-coroutines/src/commonMain/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StoreExt.kt (7 hunks)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/LabelChannelWithLifecycleTest.kt (1 hunks)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/LabelChannelWithScopeTest.kt (1 hunks)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowTest.kt (2 hunks)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithLifecycleTest.kt (1 hunks)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithScopeTest.kt (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowTest.kt
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build on Linux
  • GitHub Check: Build on macOS
🔇 Additional comments (9)
mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithScopeTest.kt (1)

1-13: LGTM! Well-organized imports.

The imports are logically grouped and include all necessary components for testing coroutines and state flow functionality.

mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/LabelChannelWithScopeTest.kt (2)

17-17: LGTM! Clear and descriptive class name.

The rename from LabelChannelTest to LabelChannelWithScopeTest better reflects the test's focus on scope-based functionality.


Line range hint 19-86: Comprehensive test coverage for the labelsChannel API.

The test suite effectively covers the critical aspects of the labelsChannel functionality:

  1. Label emission and collection
  2. Proper cleanup on scope cancellation
  3. Channel cancellation behavior

Let's verify if there are any edge cases not covered by running this analysis:

✅ Verification successful

Test coverage is comprehensive and well-structured

The test suite effectively covers all critical aspects of the labelsChannel API, including both the CoroutineScope and Lifecycle variants. The implementation's simplicity, combined with thorough testing of core functionality and cleanup scenarios, provides confidence in the code's reliability.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential edge cases in the Store interface implementation
# that might need additional test coverage

# Search for Store implementations to analyze their label handling
ast-grep --pattern 'class $_ : Store<$_, $_, $_> {
  $$$
  override fun labels($_) {
    $$$
  }
  $$$
}'

# Search for labelsChannel usage patterns to ensure test coverage is complete
rg "labelsChannel" -A 3

Length of output: 8859

mvikotlin-extensions-coroutines/src/commonTest/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StateFlowWithLifecycleTest.kt (2)

53-79: TestStore implementation looks good

The TestStore implementation correctly implements the Store interface and provides the necessary functionality for testing. The use of a nullable stateObserver with private setter is a good pattern for testing subscription behavior.


44-46: 🛠️ Refactor suggestion

Avoid infinite loops in tests

The infinite loop in the test could potentially hang if the lifecycle destruction doesn't properly cancel the flow collection.

-        scope.launch {
-            while (true) {
-                channel.receive()
-            }
-        }
+        scope.launch {
+            try {
+                flow.collect()
+            } catch (e: CancellationException) {
+                // Expected when lifecycle is destroyed
+            }
+        }

Likely invalid or redundant comment.

mvikotlin-extensions-coroutines/api/jvm/mvikotlin-extensions-coroutines.api (1)

69-73: API changes look good

The new lifecycle-aware methods are well-designed:

  1. They maintain backward compatibility by keeping existing methods
  2. They follow the same pattern for both labels and state
  3. They properly handle default parameters via synthetic methods
mvikotlin-extensions-coroutines/api/android/mvikotlin-extensions-coroutines.api (1)

69-73: Android API changes match JVM API

The Android API changes are identical to the JVM API changes, maintaining consistency across platforms.

mvikotlin-extensions-coroutines/src/commonMain/kotlin/com/arkivanov/mvikotlin/extensions/coroutines/StoreExt.kt (2)

3-4: Documentation improvements and imports look good!

The documentation changes better reflect the behavior of the methods, and the new imports are necessary for the lifecycle integration.

Also applies to: 23-26, 31-35


Line range hint 1-166: Verify test coverage for lifecycle-aware methods.

The AI summary mentions new test classes (LabelChannelWithLifecycleTest and StateFlowWithLifecycleTest), but let's verify their existence and coverage.

✅ Verification successful

Test coverage for lifecycle-aware methods is comprehensive

Both stateFlow and labelsChannel lifecycle-aware methods are thoroughly tested, covering resource cleanup, unsubscription, and cancellation behaviors.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage for new lifecycle-aware methods

# Check for test files
echo "Checking for test files..."
fd -e kt "StateFlowWithLifecycleTest|LabelChannelWithLifecycleTest"

# Look for test cases covering lifecycle destruction
echo -e "\nChecking test coverage for lifecycle destruction..."
rg -A 5 "doOnDestroy|lifecycle.*destroy" -g "*Test.kt"

Length of output: 8679

@arkivanov arkivanov merged commit 7399018 into master Jan 15, 2025
3 checks passed
@arkivanov arkivanov deleted the store-state-flow-and-labels-channel branch January 15, 2025 17:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant