Skip to content

Conversation

@gabrieleandro
Copy link
Contributor

@gabrieleandro gabrieleandro commented Jul 29, 2025

Implements native useRoomListSubscription Hook
Enhanced the subscription lifecycle by subscribing and unsubscribing based on the app's active/inactive state.
Ensures real-time updates are re-established automatically after app resumes from the background or device unlock.
Prevents missed events or stale subscriptions due to suspended WebSocket connections on iOS.

@changeset-bot
Copy link

changeset-bot bot commented Jul 29, 2025

⚠️ No Changeset found

Latest commit: ed09a8e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Jul 29, 2025

Walkthrough

A new native implementation of the useRoomListSubscription hook was introduced to manage chat room subscriptions based on application lifecycle events. Supporting utility functions were refactored for modularity, and relevant exports were updated. The package version was incremented to 1.3.0, and changelog documentation was updated accordingly.

Changes

Cohort / File(s) Change Summary
Changelog & Versioning
packages/components/CHANGELOG.md, packages/components/package.json
Updated changelog to document the new feature and incremented the package version from 1.2.9 to 1.3.0.
Web Subscription Refactor
packages/components/modules/messages/common/graphql/subscriptions/useRoomListSubscription.tsx
Refactored the web useRoomListSubscription hook by extracting subscription logic into two new exported functions: wasRemovedFromChatRoom and getRoomListSubscriptionConfig, improving modularity without altering behavior.
Native Subscription Implementation
packages/components/modules/messages/native/graphql/subscriptions/useRoomListSubscription.tsx
Added a new native-specific useRoomListSubscription hook that manages subscription and unsubscription based on app focus and lifecycle state, using Relay and custom hooks for cleanup and re-subscription.
Native Module Exports
packages/components/modules/messages/native/index.ts
Added export for the new native useRoomListSubscription hook to the module's public API.

Sequence Diagram(s)

sequenceDiagram
  participant App as App Component
  participant Hook as useRoomListSubscription (Native)
  participant Relay as Relay Environment
  participant AppState as App State Listener

  App->>Hook: Mounts component
  Hook->>Relay: Subscribes to room list
  AppState-->>Hook: App goes inactive
  Hook->>Relay: Unsubscribes from room list
  AppState-->>Hook: App returns to foreground
  Hook->>Relay: Re-subscribes to room list
  App->>Hook: Unmounts component
  Hook->>Relay: Cleans up subscription
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Suggested labels

approved

Suggested reviewers

  • anicioalexandre
  • priscilladeroode
  • deboracosilveira

Poem

A bunny hops with code so bright,
Subscriptions now respond to light—
When apps go dark, they pause the tune,
And leap back in when life resumes.
With hooks refactored, clean and neat,
This version’s hop is quite a feat!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/react-native-roomlist-subscriptions-improvement

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @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.

@gabrieleandro gabrieleandro force-pushed the feature/react-native-roomlist-subscriptions-improvement branch from 2174444 to 7847c78 Compare July 30, 2025 23:19
@gabrieleandro gabrieleandro force-pushed the feature/react-native-roomlist-subscriptions-improvement branch from 588a2bc to ed09a8e Compare July 31, 2025 22:26
@sonarqubecloud
Copy link

@gabrieleandro gabrieleandro marked this pull request as ready for review July 31, 2025 22:49
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: 0

🧹 Nitpick comments (2)
packages/components/modules/messages/common/graphql/subscriptions/useRoomListSubscription.tsx (2)

55-55: Consider using a proper error handler instead of console.error.

Using console.error directly may not be appropriate for production environments. Consider accepting an error handler as a parameter or using a centralized error reporting system.

-  onError: console.error,
+  onError: onError || console.error,

And update the function signature to include an optional error handler parameter.


57-82: Consider adding inline documentation for complex Relay operations.

The updater function contains sophisticated Relay store manipulation logic that handles both user removal and room updates. While the implementation appears correct, adding inline comments would improve maintainability.

Consider adding comments like:

  updater: (
    store: RecordSourceSelectorProxy<unknown>,
    data: useRoomListSubscription$data | null | undefined,
  ) => {
    const roomId = data?.chatRoomOnRoomUpdate?.room?.node?.id
    if (!roomId) return
+   
+   // If user was removed from the room, delete it from all connections
    if (wasRemovedFromChatRoom(data, profileId)) {
      getChatRoomConnections(store, profileId).forEach((connectionRecord) =>
        ConnectionHandler.deleteNode(connectionRecord, roomId),
      )
    } else {
+     // Otherwise, update the room by re-inserting it to maintain proper order
      const isArchived = data?.chatRoomOnRoomUpdate?.room?.node?.isArchived
      getChatRoomConnections(
        store,
        profileId,
+       // Only update connections that match the room's archived status
        ({ q, archived }) => q === '' && archived === isArchived,
      ).forEach((connectionRecord) => {
+       // Remove old edge and insert updated one at the beginning
        ConnectionHandler.deleteNode(connectionRecord, roomId)
        const serverEdge = store.getRootField('chatRoomOnRoomUpdate')?.getLinkedRecord('room')
        const edge = ConnectionHandler.buildConnectionEdge(store, connectionRecord, serverEdge)
        if (edge) {
          ConnectionHandler.insertEdgeBefore(connectionRecord, edge)
        }
      })
    }
  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ea0e291 and ed09a8e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/common/graphql/subscriptions/useRoomListSubscription.tsx (2 hunks)
  • packages/components/modules/messages/native/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/native/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/components/modules/messages/common/graphql/subscriptions/useRoomListSubscription.tsx (1)
packages/components/modules/messages/common/utils.ts (1)
  • getChatRoomConnections (60-70)
🔇 Additional comments (9)
packages/components/modules/messages/common/graphql/subscriptions/useRoomListSubscription.tsx (2)

41-45: LGTM! Clean utility function extraction.

The wasRemovedFromChatRoom function is well-implemented with proper optional chaining and clear logic for checking if the current user was removed from the chat room.


105-109: Excellent refactoring for modularity.

The extraction of subscription configuration into getRoomListSubscriptionConfig successfully modularizes the logic while maintaining the same behavior. The useMemo usage is correct with proper dependencies.

packages/components/package.json (1)

4-4: Appropriate version bump for new functionality.

The minor version increment from 1.2.9 to 1.3.0 correctly reflects the addition of the new native useRoomListSubscription hook implementation.

packages/components/CHANGELOG.md (1)

3-7: Well-documented changelog entry.

The changelog entry clearly describes the new native useRoomListSubscription hook functionality and its lifecycle-aware behavior. The description effectively communicates the purpose and benefits of the implementation.

packages/components/modules/messages/native/index.ts (1)

3-3: Correct export addition for the new native hook.

The export follows the established pattern and properly exposes the new useRoomListSubscription hook to the module's public API.

packages/components/modules/messages/native/graphql/subscriptions/useRoomListSubscription.tsx (4)

15-34: Well-structured hook implementation.

The hook signature is appropriate with necessary parameters, and the setup correctly uses the refactored getRoomListSubscriptionConfig function. The disposable ref pattern and memoization are properly implemented.


36-45: Proper subscription lifecycle management.

The subscribe/unsubscribe functions correctly handle Relay subscription disposal to prevent memory leaks. The profileId guard and useCallback usage are appropriate.


47-54: Correct focus-based subscription management.

The useFocusEffect implementation properly subscribes when the screen gains focus and unsubscribes on blur, following React Navigation best practices for lifecycle-aware subscriptions.


56-58: Addresses iOS WebSocket suspension issues effectively.

The useAppStateSubscription usage correctly handles the case where WebSocket connections are suspended when the app goes to background, re-establishing the subscription when the app returns to the foreground. This directly addresses the PR objectives.

@gabrieleandro gabrieleandro merged commit c7675e1 into master Jul 31, 2025
8 checks passed
@gabrieleandro gabrieleandro deleted the feature/react-native-roomlist-subscriptions-improvement branch July 31, 2025 23:17
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.

3 participants