Mobile view lifecycle. Fixing Xamarin.Forms Page lifecycle

For mobile applications the highest priority is user. What user can see and interacts with. Application should react not only on user interacting with it but also user interacting with operating system. That's why not only application has it's own lifecycle but also "view" has it's own lifecycle.

In Android view is represented by activity, or a fragment (the right side of android diagram). In iOS view has it's own set of lifecycle methods. In both cases view has the information that application(in this case view itself)  is being suspended and reactivated. View know quite a lot about outside world and view lifecycle is very similar to application lifecycle.
Compare below first application and then view lifecycle diagrams:
Android vs iOS lifecycle

In Android view is represented by activity, or a fragment (the right side of android diagram). In iOS view has it's own set of lifecycle methods. In both cases view has the information that application(in this case view itself)  is being suspended and reactivated. View know quite a lot about outside world.

Android Activity and Fragment lifecycle. iOS view lifecycle


In Xamarin.Forms view that is represented by Page. Unfortunately Page has only two events PageAppearing and PageDisappearing and they are connected to navigation not the application lifecycle. So Page doesn’t know a thing about application being suspended or resumed.

Android Activity and Fragment lifecycle. iOS view lifecycle. Xamarin.Forms Page lifecycle


This problem can be easily fixed passing events form Application to Page
Xamarin.Forms has it's own MessegingCenter with enables view models and other components to communicate with without having to know anything about each other besides a simple Message contract.
Application can send message with lifecycle event and every view that need's to  handle events can subscribe to MessagingCenter. 

In App.cs we add MessagingCenter.Send
In BaseContentPage we subscribe and unsubscribe for reqired message type.

After that small change we have Xamarin.Forms lifecycle as complicated as Android and iOS (and as we wanted it to be).

Comments

Alex said…
Thank you very much!

Popular posts from this blog

Azure post deployment scripts

Mobile application life-cycle Android vs iOS vs Xamarin.Forms