Skip to content

Conversation

@met94
Copy link
Contributor

@met94 met94 commented Sep 30, 2025

✨ What kind of change does this PR introduce? (Bug fix, feature, docs update...)

Bug fix
Fixes #4913

⤵️ What is the current behavior?

When a ViewModel of a specific type is already present in the cache, MvvmCross prevents caching a second instance of the same type until the first one is explicitly removed. This results in scenarios where the previously cached instance is returned, even though a new instance was intended. Consequently, the new ViewModel is not cached and may not be retrieved as expected. Additionally, the retained ViewModel remains in memory longer than necessary, which can interfere with garbage collection and lead to unintended memory retention.

🆕 What is the new behavior (if this is a feature change)?

When a ViewModel of a specific type is already cached and a new instance of the same type is requested to be cached, the new instance will now replace the existing one in the cache. This ensures that the most recent ViewModel is always retrievable and avoids unintended reuse of stale instances.

Additionally, the cached ViewModel is now explicitly removed during the OnResume lifecycle event. Since MvvmCross only attempts to retrieve cached ViewModels during OnCreate, retaining them beyond that point serves no purpose and may lead to unnecessary memory retention. This change helps reduce memory pressure and improves lifecycle alignment.

💥 Does this PR introduce a breaking change?

No

🐛 Recommendations for testing

  1. Verify ViewModel replacement in cache:

    • Create two instances of the same ViewModel type.
    • Ensure that when the second instance is cached, it replaces the first.
    • Confirm that retrieving the cached ViewModel returns the most recent instance.
  2. Validate cache clearing on OnResume:

    • Navigate away from the view and trigger OnResume.
    • Ensure the ViewModel is removed from the cache.
    • Confirm that subsequent retrieval does not return the old instance.
  3. Note on bug [Bug]: Stale ViewModel is sometimes returned from MvxMultipleViewModelCache in Android #4913 and [Bug]: Regression: typeof(TViewType) in MvxViewExtensions breaks ViewModel resolution #4957:

📝 Links to relevant issues/docs

🤔 Checklist before submitting

@github-actions github-actions bot added the p/android Android platform label Sep 30, 2025
@met94 met94 marked this pull request as ready for review September 30, 2025 14:51
@Cheesebaron Cheesebaron enabled auto-merge (squash) October 3, 2025 11:28
@Cheesebaron Cheesebaron merged commit 079fe00 into MvvmCross:develop Oct 3, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

p/android Android platform

Development

Successfully merging this pull request may close these issues.

[Bug]: Stale ViewModel is sometimes returned from MvxMultipleViewModelCache in Android

2 participants