fix: reset listener state on endConnection for proper reconnection#3151
fix: reset listener state on endConnection for proper reconnection#3151
Conversation
- Change requestPurchase return type from Promise<RequestPurchaseResult | null> to Promise<void> - This aligns with hook design where purchase results come through onPurchaseSuccess callback - Update CLAUDE.md documentation to clarify hook vs root API semantics - Fix markdownlint warning in CLAUDE.md Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Reset `listenersAttached` (Android) and `isInitializing` (iOS) flags during endConnection so that listeners can be re-registered after a subsequent initConnection call. Add reconnection listener tests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Summary of ChangesHello @hyochan, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request resolves an issue where in-app purchase event listeners would not re-establish correctly after the connection to the billing service was ended and then re-initialized. By resetting key internal state flags on both Android and iOS platforms during connection termination, the system now properly allows listeners to be re-attached. This ensures that applications reliably receive purchase and error events even after connection interruptions, enhancing the robustness of the in-app purchase flow. The changes are validated by new dedicated test cases. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3151 +/- ##
==========================================
+ Coverage 68.54% 68.67% +0.13%
==========================================
Files 9 9
Lines 1777 1778 +1
Branches 587 587
==========================================
+ Hits 1218 1221 +3
+ Misses 554 552 -2
Partials 5 5
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Code Review
The pull request correctly addresses the issue where listener state was not being reset during endConnection, which prevented proper re-registration of listeners upon reconnection. The changes in HybridRnIap.kt (Android) and HybridRnIap.swift (iOS) ensure that the initialization and listener flags are cleared. Additionally, the useIAP hook's requestPurchase method has been updated to return void, which aligns with the library's event-driven architecture where results are handled via listeners and hook state. The added tests provide good coverage for the reconnection scenario.
| runCatching { openIap.endConnection() } | ||
| productTypeBySku.clear() | ||
| isInitialized = false | ||
| listenersAttached = false |
There was a problem hiding this comment.
While resetting listenersAttached is necessary to allow re-attaching the bridge listeners to the underlying openIap module, you should also clear the internal listener lists (purchaseUpdatedListeners, purchaseErrorListeners, etc.) in endConnection.
On iOS, cleanupExistingState (called by endConnection) clears these lists. On Android, if you don't clear them, any listeners registered from the JS side before endConnection will persist. When initConnection is called again, a new bridge listener is attached to openIap, but the old JS listeners are still in the lists. This will result in duplicate notifications for the same event after reconnection.
Clearing these lists ensures consistency between platforms and prevents duplicate event delivery.
listenersAttached = false
purchaseUpdatedListeners.clear()
purchaseErrorListeners.clear()
promotedProductListenersIOS.clear()
userChoiceBillingListenersAndroid.clear()
developerProvidedBillingListenersAndroid.clear()Clear all internal listener lists (purchaseUpdated, purchaseError, promotedProduct, userChoiceBilling, developerProvidedBilling) in endConnection to match iOS cleanupExistingState behavior and prevent duplicate event delivery after reconnection. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
📝 WalkthroughWalkthroughDocumentation clarifies requestPurchase results are delivered via onPurchaseSuccess (not return value). requestPurchase signature changed to return Promise. Native endConnection/cleanup now clears initialization and all listener state. Tests added verifying listeners survive endConnection + reconnect cycles. Changes
Sequence Diagram(s)sequenceDiagram
participant App as App (UI)
participant Hook as useIAP (JS)
participant Native as HybridRnIap (Native)
participant Store as Billing Store (Google/Apple)
App->>Hook: call requestPurchase(sku)
Hook->>Native: requestPurchaseInternal(sku)
Native->>Store: initiate purchase flow
Store-->>Native: purchase success event
Native-->>Hook: emit onPurchaseSuccess(product)
Hook-->>App: onPurchaseSuccess callback invoked
App->>Hook: call endConnection()
Hook->>Native: endConnection()
Native-->>Native: clear listeners, set listenersAttached=false, isInitializing=false
App->>Hook: re-init connection
Hook->>Native: initConnection()
Native-->>Native: re-register native listeners
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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. Comment |
|
Addressed Gemini's review feedback in 2e6a92c — now clearing all five internal listener lists ( |
Add test verifying useIAP's requestPurchase calls root API and returns void, covering the async/await wrapper changed in the requestPurchase return type update. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/__tests__/hooks/useIAP.test.ts (1)
137-140: Move theexpectassertion outside ofact.
act()is intended to wrap operations that trigger React state changes. The assertionexpect(result).toBeUndefined()is pure test logic and is more readable and conventional when placed after theactblock.♻️ Proposed refactor
- await act(async () => { - const result = await api.requestPurchase({sku: 'product1'}); - expect(result).toBeUndefined(); - }); + let result: unknown; + await act(async () => { + result = await api.requestPurchase({sku: 'product1'}); + }); + expect(result).toBeUndefined();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/__tests__/hooks/useIAP.test.ts` around lines 137 - 140, The assertion is inside the React testing act wrapper; move the pure test assertion outside of act to improve readability: keep the async call to api.requestPurchase({sku: 'product1'}) inside await act(async () => { ... }) but capture its return (e.g., assign result) and then call expect(result).toBeUndefined() after the act block; adjust the test around the api.requestPurchase call and the result variable so the only code inside act is the operation that triggers state changes and the expect runs immediately afterward.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/__tests__/hooks/useIAP.test.ts`:
- Around line 122-124: Replace the mock that resolves to null with one that
resolves to undefined so it matches the Promise<void> typing for
IAP.requestPurchase; locate the spy on IAP.requestPurchase (assigned to
mockRequestPurchase) in the useIAP.test.ts test and change its
mockResolvedValue(null as any) to mockResolvedValue(undefined) (or use
jest.fn(() => Promise.resolve()) pattern) to keep semantics consistent with the
project setup.
---
Nitpick comments:
In `@src/__tests__/hooks/useIAP.test.ts`:
- Around line 137-140: The assertion is inside the React testing act wrapper;
move the pure test assertion outside of act to improve readability: keep the
async call to api.requestPurchase({sku: 'product1'}) inside await act(async ()
=> { ... }) but capture its return (e.g., assign result) and then call
expect(result).toBeUndefined() after the act block; adjust the test around the
api.requestPurchase call and the result variable so the only code inside act is
the operation that triggers state changes and the expect runs immediately
afterward.
The root API requestPurchase returns Promise<Purchase | null>, so null is the correct mock value without needing a type cast. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
Summary
listenersAttachedflag (Android) andisInitializingflag (iOS) duringendConnectionso listeners can be re-registered after reconnectionendConnection → initConnectioncycleChanges
Android (
HybridRnIap.kt)listenersAttached = falseinendConnectionto allow re-attachment on nextinitConnectioniOS (
HybridRnIap.swift)isInitializing = falseinendConnectionto allow re-initializationTests (
index.test.ts)endConnection → initConnectionendConnection → initConnectionTest plan
yarn typecheckpassesyarn lintpassesyarn testpasses (new reconnection tests included)🤖 Generated with Claude Code
Summary by CodeRabbit
Documentation
Bug Fixes
Breaking Changes
Tests