Skip to content

Unity native variables sync #160

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

Merged
merged 6 commits into from
Mar 25, 2025

Conversation

nzagorchev
Copy link
Contributor

@nzagorchev nzagorchev commented Mar 14, 2025

Summary by CodeRabbit

  • New Features

    • The "Variables" button is now consistently interactive for a more responsive navigation experience.
    • Introduced a new event type for variable definition events, enhancing variable synchronization.
    • Added functionality to flatten nested variable dictionaries for improved payload management.
  • Bug Fixes

    • Implemented additional null checks and refined error handling for variable updates and network requests, reducing potential crashes and providing clearer error messages.

These updates improve the reliability and responsiveness of variable interactions and event processing for a smoother user experience.

@nzagorchev nzagorchev requested a review from vasct March 14, 2025 09:38
Copy link

coderabbitai bot commented Mar 14, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces multiple improvements across the codebase. UI behavior is adjusted by removing a conditional disable in the navigation menu, while variable handling is enhanced with additional null checks and conditional logic. New utility methods for type determination and flattening nested dictionaries have been added, alongside new classes and methods to support event queue management and variable synchronization. Enhanced error logging and detailed network response handling are also present, with new tests ensuring the expected behavior of the variable utilities.

Changes

File(s) Change Summary
CTExample/Assets/Scripts/NavigationMenu.cs
CTExample/Assets/Scripts/Variables/Variables.cs
Removed conditionally compiled code that disabled the "Variables" button; added null checks in event subscriptions, conditional Sync calls, and null-safe UI updates.
CleverTap/Runtime/Common/CleverTapPlatformVariable.cs
CleverTap/Runtime/Common/VariableFactory.cs
CleverTap/Runtime/Constants/CleverTapVariableKind.cs
Introduced GetKindNameFromType for centralized type-checking; updated variable instantiation with error logging and refined platform-specific logic; added XML documentation and reformatted namespace block.
CleverTap/Runtime/Native/UnityNativePlatformBinding.cs
CleverTap/Runtime/Native/UnityNativePlatformVariable.cs
Added an internal property exposing UnityNativeWrapper; introduced a new constructor and field for unityNativeWrapper with updated SyncVariables logging and error handling.
CleverTap/Runtime/Native/UnityNativeWrapper/Enums/UnityNativeEventType.cs
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs
Expanded the event type enum with DefineVarsEvent and integrated a new switch case handling for this event type.
CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs
CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs.meta
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs
Added a new UnityNativeSingleEventQueue class with methods for event queuing, flushing, and response processing; introduced SyncVariables in the event manager and a dedicated single events queue in the queue manager with timer-based flushing.
CleverTap/Runtime/Native/UnityNativeNetworkEngine.cs
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVarCache.cs
Modified error handling in SendRequest to use null-conditional operators and include HTTP-specific response details; added a new method to fetch a flattened define-vars payload with conditional namespace inclusion.
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVariableUtils.cs
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeWrapper.cs
Introduced methods to flatten nested dictionaries, generate flat variable payloads, and determine types based on CleverTap variable kinds; added a new SyncVariables method to pass payloads via the event manager.
CleverTap/Tests/Runtime/UnityNativeVariableUtilsTest.cs Added new test methods (GetFlatVarsPayload and GetFlatVarsPayload_Empty) to validate the flattened variable payload generation in various scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Wrapper as UnityNativeWrapper
    participant Manager as UnityNativeEventManager
    participant QueueMgr as UnityNativeEventQueueManager
    participant SingleQ as UnityNativeSingleEventQueue
    participant Network as UnityNativeNetworkEngine

    Wrapper->>Manager: SyncVariables(varsPayload)
    Manager->>QueueMgr: Create DefineVarsEvent with payload
    QueueMgr->>SingleQ: Enqueue DefineVarsEvent
    SingleQ->>QueueMgr: [Timer Tick] Trigger Flush
    QueueMgr->>Network: SendRequest(event)
    Network-->>QueueMgr: Response
Loading

Suggested reviewers

  • vasct

Poem

Hopping through lines of code so spry,
I nibble bugs and watch them fly.
New methods bloom like clover in spring,
Events queue up, and functions sing.
With keen eyes and a joyful heart,
This rabbit cheers the code’s fresh start!
🐇✨


🪧 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.
  • @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.

@nzagorchev
Copy link
Contributor Author

@CodeRabbit review

Copy link

coderabbitai bot commented Mar 14, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (3)
CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs (3)

14-14: Reconfirm the constant queue limit.
Hardcoding QUEUE_LIMIT = 1 is consistent with this "single event" logic, but if there is any possibility of extending this queue in the future, consider making it configurable.


91-92: Fix the spelling in the success message.
"Varibles" should be "Variables" to maintain professional log output.

- CleverTapLogger.Log("Varibles Successfully synced");
+ CleverTapLogger.Log("Variables successfully synced");

116-127: Consider handling or awaiting the FlushEvents task.
The call to FlushEvents() is invoked with _ = ..., discarding the returned Task. If an exception occurs, it might be lost. Consider awaiting this call or adding error handling to catch potential failures.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93f7d23 and 665e5a5.

📒 Files selected for processing (18)
  • CTExample/Assets/Scripts/NavigationMenu.cs (0 hunks)
  • CTExample/Assets/Scripts/Variables/Variables.cs (2 hunks)
  • CleverTap/Runtime/Common/CleverTapPlatformVariable.cs (1 hunks)
  • CleverTap/Runtime/Common/VariableFactory.cs (1 hunks)
  • CleverTap/Runtime/Constants/CleverTapVariableKind.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativePlatformBinding.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativePlatformVariable.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Enums/UnityNativeEventType.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs.meta (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (2 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (3 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeNetworkEngine.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVarCache.cs (2 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVariableUtils.cs (3 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeWrapper.cs (2 hunks)
  • CleverTap/Tests/Runtime/UnityNativeVariableUtilsTest.cs (2 hunks)
💤 Files with no reviewable changes (1)
  • CTExample/Assets/Scripts/NavigationMenu.cs
🔇 Additional comments (39)
CleverTap/Runtime/Native/UnityNativeWrapper/Enums/UnityNativeEventType.cs (1)

13-14: LGTM - Event type enum addition

The addition of DefineVarsEvent to the enum follows the existing pattern of sequential numbering and maintains code consistency.

CleverTap/Runtime/Constants/CleverTapVariableKind.cs (1)

1-9: Code documentation improvement

Good addition of XML documentation comments that clearly explain the purpose and usage of the CleverTapVariableKind class. The namespace reformatting also improves code readability.

CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs.meta (1)

1-11: Auto-generated Unity meta file

This is a standard Unity-generated meta file for the new UnityNativeSingleEventQueue class. It contains the necessary Unity asset metadata and doesn't require modifications.

CleverTap/Runtime/Native/UnityNativePlatformBinding.cs (1)

9-10: Appropriate accessor added for internal use

Adding this property allows other components to access the UnityNativeWrapper instance while maintaining proper encapsulation. This change enables the new variable synchronization functionality without exposing the wrapper instance beyond its needed scope.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeWrapper.cs (1)

45-49: Good implementation of variable synchronization method

This method properly delegates to the event manager's SyncVariables method, enabling variable synchronization functionality without duplicating logic. The method signature correctly accepts a dictionary payload that can contain all necessary variable data.

CTExample/Assets/Scripts/Variables/Variables.cs (4)

155-156: Good null check added to prevent potential exceptions

Adding this null check prevents a NullReferenceException when attempting to subscribe to the OnFileReady event if factory_var_file is null. This is a good defensive programming practice.


164-169: Platform-specific implementation for variable synchronization

The conditional compilation directive ensures that iOS platforms use a different synchronization method (with the force parameter set to true) compared to other platforms. This addresses platform-specific requirements for variable synchronization.


225-228: Improved null handling with null-conditional operators

Using the null-conditional operator (?.) is a good approach to prevent null reference exceptions when accessing properties of potentially null variables. This makes the code more robust against runtime errors.


233-235: Appropriate validation added to prevent errors

Adding this null check ensures that the method returns early when the name parameter is null or empty, preventing potential issues when attempting to use the name later in the method. This improves the robustness of the code.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVarCache.cs (3)

1-2: Proper platform-specific code isolation

The preprocessor directive ensures this code only runs on appropriate platforms (not on iOS/Android or when in the Unity Editor). Adding System.Collections namespace is necessary for handling collections properly.


137-140: Well-implemented method for variable payload retrieval

This method provides a clean way to get a flattened version of the variable payload by delegating to the UnityNativeVariableUtils helper. This supports the variable synchronization feature and follows good separation of concerns.


142-143: Properly closed preprocessor directive

The closing preprocessor directive correctly matches the opening directive, ensuring the platform-specific code is properly encapsulated.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeNetworkEngine.cs (2)

372-373: Good improvement to error handling with the null-conditional operator

The addition of the null-conditional operator ?. when accessing unityWebRequest.downloadHandler.text prevents potential NullReferenceExceptions. Additionally, the response now correctly includes the actual HTTP status code and response headers, providing more detailed error information.


377-377: Enhanced error response with actual HTTP status code

This change improves error reporting by using the actual HTTP response code rather than defaulting to InternalServerError, which provides more accurate context for debugging issues.

CleverTap/Runtime/Common/VariableFactory.cs (2)

7-7: Added utility namespace import

The addition of the CleverTapSDK.Utilities namespace import allows for using the logger functionality that's used later in the code.


24-30: Added null check and error logging for UnityNativePlatformBinding

This improvement adds proper error handling when the binding isn't of the expected type. The null-conditional operator ensures safe access to UnityNativeWrapper, preventing potential NullReferenceExceptions.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (2)

6-7: Moved imports under the platform-specific directive

Moving these imports under the platform-specific directive ensures they're only included when needed for the targeted platform.


103-115: Added SyncVariables method for variable synchronization

This new method properly handles the synchronization of variables by:

  1. Checking if the event should be deferred
  2. Building an event of type DefineVarsEvent with the payload
  3. Queuing the event for processing

The implementation follows the established pattern in the codebase for other event types and properly handles deferred events.

CleverTap/Runtime/Common/CleverTapPlatformVariable.cs (2)

145-146: Refactored type checking to call the new GetKindNameFromType method

Good refactoring to call the centralized type checking method that's been added.


148-172: Added centralized type checking method with comprehensive type support

The new GetKindNameFromType method centralizes the logic for determining variable types, making the code more maintainable. It properly handles various numeric types, strings, dictionaries, and booleans.

This method supports better code reuse and consistency in type determination across the SDK.

CleverTap/Tests/Runtime/UnityNativeVariableUtilsTest.cs (2)

3-7: Appropriate imports added for new test functionality.

The additional imports provide necessary access to the CleverTap SDK common classes, constants, and Unity functionality required for the new tests.


365-471: Well-structured test cases for the new GetFlatVarsPayload functionality.

The test cases comprehensively cover:

  1. Various variable types (string, int, dictionary, float)
  2. Nested dictionary flattening
  3. Empty dictionary handling
  4. Proper type conversion from CleverTap variable kinds to payload types

The test assertions are thorough and verify both the structure and content of the output payload. This ensures that variable synchronization with native platforms will work correctly.

CleverTap/Runtime/Native/UnityNativePlatformVariable.cs (5)

4-7: Added necessary Unity import.

The addition of Unity's namespace provides access to Debug functionality used for distinguishing between debug and release builds.


11-12: Added dependency for variable synchronization.

The unityNativeWrapper field enables the class to access native platform capabilities for variable synchronization.


13-16: Good use of dependency injection for testability.

The constructor properly initializes the native wrapper, allowing for better testability by injecting dependencies.


19-21: Simplified method now delegates to the overloaded version.

The method has been refactored to call the parameterized version with a default value, improving code reuse.


25-56: Enhanced error handling and robust environment checks.

The implementation now:

  1. Verifies build environment (debug vs release) and provides appropriate warnings
  2. Checks for null references before attempting operations
  3. Provides clear error messages for different failure scenarios

This helps developers understand when and how to use the SyncVariables method correctly.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (5)

12-13: Added dedicated queue for single events.

This new queue allows for specialized handling of events that should be processed individually, such as variable definitions.


21-22: Proper initialization and event subscription for the new queue.

The queue is correctly initialized with core state and network engine, and properly subscribed to the timer tick event.


27-29: Refactored event handling to use centralized method.

The method now delegates to the new QueueEvent method, improving maintainability and reducing code duplication.


31-47: Well-structured event routing based on event type.

The new QueueEvent method routes events to the appropriate queue based on event type, including the new DefineVarsEvent type.


63-66: Added timer tick handler for single events queue.

This handler follows the established pattern for other event queues, ensuring consistent behavior.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVariableUtils.cs (4)

1-7: Appropriate platform-specific compilation directive and imports.

The code correctly uses preprocessor directives to exclude the implementation from mobile platforms except in the Unity Editor. The necessary imports have been added for the new functionality.


95-110: Well-implemented dictionary flattening method.

The ConvertNestedDictionariesToFlat method recursively processes nested dictionaries, maintaining key hierarchy through dot notation. This creates a flat representation suitable for variable synchronization with native platforms.


112-157: Comprehensive implementation of variable payload creation.

The GetFlatVarsPayload method:

  1. Properly initializes the payload structure
  2. Handles different variable types appropriately
  3. Flattens nested dictionary values
  4. Applies correct type conversions for each variable

The implementation handles all the complexity of creating a correctly structured payload for native variable synchronization.


257-271: Clean implementation of type conversion using switch expression.

The GetDefineTypeFromKind method efficiently maps CleverTap variable kinds to their corresponding payload type strings. The use of a switch expression with pattern matching is concise and readable.

CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs (3)

1-9: Conditional compilation block and using directives look good.
No issues spotted with the conditional compilation directives or the using statements.


21-37: Ensure fallback logic is acceptable.
When the queue contains more or fewer events than the limit, this method logs an error and continues with the default record path. Verify that silently falling back to REQUEST_PATH_RECORD is the desired behavior instead of, for instance, throwing an exception or discarding the extra events.


44-59: Response check logic is consistent.
The gating on exactly one event matches the single-event assumption. Logging an error and relying on response.IsSuccess() otherwise appears correct.

@nzagorchev
Copy link
Contributor Author

@CodeRabbit review

Copy link

coderabbitai bot commented Mar 14, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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 (6)
CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeBaseEventQueue.cs (1)

75-75: Minor spelling fix suggested.
The variable is named proccesedEvents; consider renaming it to processedEvents for clarity.

- var proccesedEvents = new List<UnityNativeEvent>();
+ var processedEvents = new List<UnityNativeEvent>();
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (5)

47-64: New QueueEvent method consolidates event handling.
Distinct event types are dispatched to their respective queues. Consider logging an appropriate message in the default: case if event types expand in the future.

 default:
+    CleverTapLogger.Log($"Unhandled event type: {newEvent.EventType}");
     break;

65-70: Use of async void for flush operations.
async void can hide exceptions and complicate error handling. Consider returning a Task instead for improved resiliency.

-internal async void FlushQueues()
+internal async Task FlushQueues()

72-75: Timer callback uses async void.
Similar best practice considerations apply here. Converting to a Task return type can help ensure proper exception propagation.


77-80: OnRaisedEventTimerTick also declared as async void.
Consider refactoring to async Task and await the caller to handle potential exceptions.


82-85: OnSingleEventTimerTick.
Same rationale: async Task is safer for asynchronous flow control, enabling external callers to handle errors.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 665e5a5 and e2ed89f.

📒 Files selected for processing (5)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeBaseEventQueue.cs (6 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeUserEventQueue.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeDatabaseStore.cs (4 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeUserEventQueue.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeSingleEventQueue.cs
🔇 Additional comments (21)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeDatabaseStore.cs (7)

14-14: Method name correction is clear and concise.
Renaming InitilazeDatabase to InitializeDatabase improves overall clarity.


21-35: Mismatch with AI-generated summary.
The summary indicates that the message "Database not intiallised" was changed to "Database not initialized" in the AddEvent method, but here we still see "intiallised."

Likely an incorrect or invalid review comment.


29-29: Conditional event invocation is appropriate.
Using OnEventStored?.Invoke(storedEvent); is a clean and safe approach.


56-56: Spelling fix for error message is correct.
Changing "Database not intiallised" to "Database not initialized" is consistent.


67-67: Fallback for null event ID.
Storing -1 when events.Id is null may be functional, but verify that using -1 for deletion does not cause other unintended side effects in your system.

Would you like me to confirm downstream handling of this fallback value?


75-75: Improved function naming.
Renaming this private method to InitializeDatabase increases readability.


83-83: Comment formatting revised.
The clarified comment about creating a table if it does not exist is helpful.

CleverTap/Runtime/Native/UnityNativeWrapper/Models/UnityNativeBaseEventQueue.cs (5)

14-14: Delegate addition.
Introducing EventsProcessed improves the event-driven approach and makes it easier to handle flushed events downstream.


31-31: New event for event processing.
OnEventsProcessed provides a valuable callback to notify subscribers when flush operations finish.


114-114: Event callback on error.
Invoking OnEventsProcessed here ensures consistent notifications even in error scenarios.


136-136: Consistent event invocation.
This helps keep the logic uniform, notifying about processed events after the exception handling block.


151-151: Final flush notification.
This invocation ensures subscribers are informed when the flush concludes, successful or otherwise.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (9)

2-2: Added namespace import.
Importing System.Collections.Generic aligns with the new usage of lists in this file.


6-8: Namespace and class scope adjustments.
These lines help structure the expanded event queue functionality.


14-14: Single events queue field addition.
The _singleEventsQueue field supports DefineVarsEvent handling in a dedicated queue.


16-35: Constructor additions for new queue and subscriptions.
Initializing _singleEventsQueue and subscribing to event callbacks centralizes queue management and deletion flow.


37-40: Database cleanup upon events processed.
Calling _databaseStore.DeleteEvents(flushedEvents); addresses potential data buildup, ensuring a consistent approach across all queues.


42-45: Forwarding newly stored events to the correct queue.
This logic simplifies event routing, ensuring that all events pass through QueueEvent.


87-91: FlushUserEvents captures user event logic.
No issues found; usage of Task return helps error handling.


93-97: FlushRaisedEvents is properly asynchronous.
This method also benefits from the Task approach, as recommended above.


99-102: FlushSingleEvents method.
Now includes a flush for single events, complementing the changes in the constructor and OnEventsProcessed.

@nzagorchev nzagorchev force-pushed the unity_native_variables branch 2 times, most recently from d9c93dc to 5a1a75e Compare March 24, 2025 13:35
@nzagorchev nzagorchev force-pushed the unity_native_variables_sync branch from 39fa71f to 13b9260 Compare March 24, 2025 13:42
@nzagorchev nzagorchev merged commit 688f805 into unity_native_variables Mar 25, 2025
1 check passed
nzagorchev added a commit that referenced this pull request Mar 31, 2025
* Merge pull request #153 from CleverTap/setup_tests

* Merge pull request #152 from CleverTap/unity_native_variables_define

* Merge pull request #156 from CleverTap/unity_native_variables_merge

* EventQueue changes (#159)

* Unity native variables sync (#160)

* Unity Native Variables - Handle Variables responses and Trigger Callbacks (#167)

* Unity native variables fetch (#168)

* Unity Native Variables - define and sync File variables (#169)

* Launch on Unity Native only (#170)

* Fix defineVars CORS issue (#174)
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.

2 participants