有時,當活動被破壞(不知道爲什麼,我假設的內存壓力)時,會創建一個新活動,但綁定到活動活動的舊視圖模型會被重用。舊的ViewModel被重用,而不是構建新的視圖
活動:
[Activity(
LaunchMode = LaunchMode.SingleTask,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
public class HomeView : MvxTabsFragmentActivity
{
protected override void OnCreate(Bundle bundle)
{
Log.Info("On HomeView created");
base.OnCreate(bundle);
}
protected override void OnDestroy()
{
base.OnDestroy();
Log.Info("On HomeView destroyed");
this.HomeViewModel.CleanUp();
}
}
視圖模型:
public class HomeViewModel : MvxViewModel
{
public HomeViewModel(
IMvxMessenger messenger,
IUserInteraction userInteraction,
DashboardViewModel dashboardViewModel,
AlertSettingsViewModel alertSettingsViewModel)
{
Log.Info("Building home view model");
}
public void CleanUp()
{
Log.Info("HomeViewModel => Clean-up");
}
}
App.cs:
public override void Initialize()
{
this.CreatableTypes().EndingWith("ViewModel").AsTypes().RegisterAsDynamic();
this.RegisterAppStart<HomeViewModel>();
TaskScheduler.UnobservedTaskException +=
(sender, eventArgs) =>
Log.Error("An Unobserved exception has been raised by a task", eventArgs.Exception);
}
調試輸出:
On HomeView created
Building home view model
...
On HomeView destroyed
HomeViewModel => Clean-up
...
On HomeView created
[here: no "Building view model" message]
也許這是SingleTask活動?
有沒有一種方法(與IoC或其他)在每個HomeView創建中獲得全新視圖模型?
編輯:
我跑過去對MvxActivityViewExtensions.cs
public static void OnViewCreate(this IMvxAndroidView androidView, Bundle bundle)
{
MvxActivityViewExtensions.EnsureSetupInitialized(androidView);
MvxActivityViewExtensions.OnLifetimeEvent(androidView, (Action<IMvxAndroidActivityLifetimeListener, Activity>) ((listener, activity) => listener.OnCreate(activity)));
IMvxViewModel cached = Mvx.Resolve<IMvxSingleViewModelCache>().GetAndClear(bundle);
IMvxView view = (IMvxView) androidView;
IMvxBundle savedState = MvxActivityViewExtensions.GetSavedStateFromBundle(bundle);
MvxViewExtensionMethods.OnViewCreate(view, (Func<IMvxViewModel>) (() => cached ?? MvxActivityViewExtensions.LoadViewModel(androidView, savedState)));
}
此方法,以便將它意味着我的視圖模型被緩存?如何禁用此緩存?
感謝您的輸入。所以在我的情況下,每次HomeView碰到OnCreate方法時都應該建立ViewModel。不幸的是,這沒有發生。我跑過了MvxActivityViewExtensions上的OnViewCreate,看到我編輯過的帖子。 – Roubachof
我不完全確定你在做什麼 - 你是否從一個HomeViewModel導航到另一個?使用'IMvxSingleViewModelCache'的唯一時間是用於活動重新創建(已保存的實例狀態場景)。如果你想避免這種情況,你可以 - 只要將'null'作爲'bundle'參數傳遞給'base.OnCreate(null);' - 但這對於Android用戶來說是非典型的用戶體驗。 – Stuart
哦,我明白了。我忘了Android中的娛樂生命週期。我以爲只有在問一個全新的視圖時才能進入消滅/創建階段。但就我而言,這確實是一種恢復狀態過程的娛樂活動。所以我已經更新了我的虛擬機來支持這個(在OnDestroy/OnCreate中使用方法CleanUp/Reload)。 – Roubachof