I’ve created a small project called TinyPubSub that only does one thing at the moment. It’s made especially for use with MVVM and Xamarin Forms.
DISCLAIMER: This is a very early version of the library.
Short version:
Long version:
I’m a big fan of vanilla MVVM. That means that I don’t like to add other frameworks on top of what’s already possible to achieve using only Xamarin Forms.
A very common scenario is that I have a main page that are supposed to display some kind of data, let’s say a list of ducks. I then navigate down a couple of pages in the app and find a page where I can add a duck. This should then update the first page. I could do this update in the OnAppearing event of the page but that breaks two nice rules of mine:
- The page should not start to load data when it is resurfaced. It should have already done that.
- The view is starting to handle logic. We don’t want that.
So I created a small (tiny one might call it) library that solves this in the most simple way I can think of. It also handles dereferencing in a nice way. As long as you don’t use Navigation.PopToRoot(); for the time being.
The features being:
- Simple usage
- Automatic un-subscription
The code
This is the structure of the project in the sample supplied with the source code (available at
github).
Initialization
To initialize TinyPubSubs automatic dereference magic, just add this code to each NavigationPage you create. I’m looking at creating a forms library that adds an Init-method instead. But for now, do this.
public App ()
{
// The root page of your application
var navPage = new NavigationPage(new MainView());
navPage.Popped += (object sender, NavigationEventArgs e) => TinyPubSub.Unsubscribe(e.Page.BindingContext);
MainPage = navPage;
}
Usage in the ViewModels
In the constructor of the ViewModels, add subscriptions like this
public MainViewModel ()
{
TinyPubSub.Subscribe (this, “update–ducks“, () =>
{
// Get data and update the GUI
});
}
The “update-ducks” string is just a arbitrary name and you can select what ever you want. Note that I don’t pass any data (yet), but that might be the next step in destroying this library by bloating it.
Publish events
In another ViewModel we then decide to add a duck.
public ICommand AddDuck
{
get {
return new Command (async () => {
// Do logic and add stuff
// Publish an event
TinyPubSub.Publish (“update–ducks“);
await Navigation.PopAsync();
});
}
}
This will fire the actions (synchronous at the moment) and then pop this view. The cool part is that when we pop the view, the subscriptions will be unsubscribed (remember the code in the beginning of the post) and the memory will be cleaned up.
This is a simple way to solve a common problem. There is a built in Messaging Center in Xamarin Forms that I personally find a bit messy to use.
Future features might be async actions and passing of simple data.