CrossPlatformLiveData — Xamarin lightweight MVVM library

Jakub Dorda
3 min readFeb 20, 2020

--

Photo by NASA on Unsplash

LiveData is one of the architecture components included in Android Jetpack. It was introduced by Google alongside with official recommendation to use MVVM architecture pattern while developing Android apps. LiveData not only solves issue of tight coupling between UI and logic layers, it’s biggest strength is ability to emit data only when UI is able to consume it. In other words using ReaciveX terminology, LiveData is a reactive subject with added subscriber lifecycle awareness.

If you need rehearsal on MVVM and LiveData, I recommend reading exceptional article by Hazem Saleh on the subject: https://proandroiddev.com/mvvm-architecture-viewmodel-and-livedata-part-1-604f50cda1

What about Xamarin?

Now imagine you are developing an app for both Android and iOS using Xamarin framework. Natural thing to do would be to place ViewModel classes in logic/core subproject, decoupled from mobile apps implementations. And here CrossPlatformLiveData comes into play! This little library enables you to have all benefits of MVVM architecture, as if you were developing native Android app on both platforms, while reusing as much codebase as possible.

CrossPlatformLiveData — C# LiveData implementation

The idea is simple, keep ViewModel classes in separate logic/core subproject, while exposing LiveData in public fields for View implementations to observe. Obviously ViewModels can not have any knowledge of, or dependency on Views. LifecycleManager acts as middleman between different View lifecycle implementations and LiveData observer.

For example, let’s say user is pressing a button which triggers web API call. Here is where MVVM magic happens, that button press is calling public ViewModel method which triggers asynchronous network call. After call completes (successfully or not) response is posted on LiveData and View observing it is notified that new data is available. Everything happens asynchronously without need to block UI. Even better, user might navigate to different fragment or open different app, response will be preserved in LiveData cache until observing View will become “active” again and ready to consume new data.

Installation

You can import CrossPlatformLiveData into your project by simply adding a nuget into logic/core subproject. LifecycleManager implementations are provided in CrossPlatformLiveData.Andorid and CrossPlatformLiveData.iOS nugets and should be imported by each platform subproject.

Usage

CrossPlatformLiveData interface is almost identical as original LiveData’s.

In Android LiveDataSupportFragment or iOS LiveDataViewController class, observe LiveData streams with LifecycleManager.

That’s it! Simple right?

Sample project is available as part of CrossPlatformLiveData repository and demonstrates both Android and iOS apps examples.

--

--