MvvmCross ViewModel caching and re-initializing

后端 未结 2 1086
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 06:44

I need to be able to intercept the framework and perform so re-initialization when a ViewModel is being reloaded from the cache. Since the ViewModel is not being recreated,

2条回答
  •  我在风中等你
    2021-01-13 07:09

    Even knowing that this question is 3 years old, I'm not sure if there's a way to do it in the current version, but I did it by myself. In this example, I'll create a static class that holds all the instances of the ViewModels in the application. It starts with null static variables and gets each value when each ViewModel is instantiated (on the constructor method).

    public static class ViewStackService
    {
        //Stack
        private static exmp1ViewModel exmp1 = null;
        private static exmp2ViewModel exmp2 = null;
        private static exmp3ViewModel exmp3 = null;
    
        public static void addStackLevel(exmp1ViewModel _parent)
        {
            exmp1 = _parent;
        }
    
        public static void addStackLevel(exmp2ViewModel _parent)
        {
            exmp2 = _parent;
        }
    
        public static void addStackLevel(exmp3ViewModel _parent)
        {
            exmp3 = _parent;
        }
    
    
        public static async void burnAll()
        {
    
            if (exmp3 != null)
            {
                exmp3.DoBackCommand();
                await Task.Delay(250);
                exmp3 = null;
            }
            if (exmp2 != null)
            {
                //the OnResume method can be implemented here
                exmp2.DoBackCommand();
                await Task.Delay(250);
                exmp2 = null;
            }
            if (exmp1 != null)
            {
                //the OnResume method can be implemented here
                exmp1.DoBackCommand();
                await Task.Delay(250);
                exmp1 = null;
            }
        }
    }
    

    These ViewModels used as variables receive the Instances when a constructor of each ViewModel is launched:

    public class exmp1ViewModel 
        : MvxViewModel
    {
        public exmp3ViewModel (){
            ViewStackService.addStackLevel (this);
        }
    }
    

    The Method burnAll() will close all the ViewModels when Called. It's problematic because as I set the time that the thread will wait manually, it can have a bug in some diferent devices, deppending on its performance. But using that class, you can do some other things, like checking whether a ViewModel was already instantiated before to instantiate a new one or use the class to implement an OnResume method to be called when a ViewModel is shown again. Just keep in mind that an instance can only be used when it's not paused,that is, you can only call methods of a ViewModel when it's being used by the app.

提交回复
热议问题