-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MvxSingleViewModelCache.cs
48 lines (40 loc) · 1.36 KB
/
MvxSingleViewModelCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
#nullable enable
using MvvmCross.ViewModels;
namespace MvvmCross.Platforms.Android.Views
{
public class MvxSingleViewModelCache
: IMvxSingleViewModelCache
{
private const string BundleCacheKey = "__mvxVMCacheKey";
private int _counter;
private WeakReference<IMvxViewModel>? _currentViewModel;
public void Cache(IMvxViewModel toCache, Bundle bundle)
{
_currentViewModel = new WeakReference<IMvxViewModel>(toCache);
_counter++;
bundle.PutInt(BundleCacheKey, _counter);
}
public IMvxViewModel? GetAndClear(Bundle? bundle)
{
try
{
if (bundle == null)
return null;
if (_currentViewModel?.TryGetTarget(out var storedViewModel) == true)
{
var key = bundle.GetInt(BundleCacheKey);
var toReturn = key == _counter ? storedViewModel : null;
return toReturn;
}
}
finally
{
_currentViewModel = null;
}
return null;
}
}
}