Custom Routing in ReactiveUI

26 Apr 2017

Out of the box, ReactiveUI provides some support for view model-first routing. A view model that implements IScreen manages a routing stack, where each view model within the stack implements IRoutableViewModel. In the view layer, a RoutedViewHost manifests a given routing stack using the idioms of the platform in question.

All this is well and good, but it does come with some limitations. Foremost, there is no support for anything specific to the platform. For example, if you want to route to a particular view on iOS without animation, you can’t do that because it’s platform-specific. Also, if you want to show a view model in a modal context, that is not supported.

These limitations are acknowledged by the ReactiveUI team and there are plans to completely revamp the routing infrastructure at a later date (probably as part of version 9). However, I needed a richer and more reliable routing system in the here-and-now, so have implemented my own. I am often queried regarding the nature of my solution, so this post is an elaboration thereof.

Note that I work mostly with Xamarin.Forms, so my solution hinges upon that fact. However, I believe the abstractions are largely platform-agnostic, so could very well be applied in other contexts (such as Xamarin.iOS). Note also that I have catered for myself and only myself here. The point of this post is not to provide something that works perfectly well for all scenarios. It is more to demonstrate the relative ease with which a bespoke routing solution can be constructed.

The Solution

The first moving parts in my solution are the interfaces that view models implement to participate in routing:

View models can be modal or non-modal and they choose an interface accordingly. Since the interface is identical, I could collapse these two interfaces into one, but in practice I find the distinction somewhat useful to code readability. In either case, the view model simply provides a string identifier. We’ll see how this is used shortly.

The IViewStackService interface defines the API with which view models will instigate changes to the view stacks (a.k.a. the navigation stacks). Notice it provides a means of changing both the page stack, and the modal stack. Each stack is represented as an observable of a list of items.

The service itself (whose implementation we’ll see shortly) is merely an admistrator of state. It is completely independent of the UI layer. It’s gateway to enacting state changes in the view is via the IView interface, upon which its implementation depends. You’ll notice that IView has an API similar to IViewStackService. The idea is that the view stack service manages the state of the stacks and dictates to the view when it should make changes to the stacks.

As you can see, there’s not a lot of complexity here. The view stack service forwards changes onto the view, and manages state for those changes. Note the need for the service to hook into a PagePopped observable provided by the view. A page might be popped in response to a direct call against ViewStackService.PopPage, but it might also be popped in response to the user tapping a system-provided back button. Regardless of how the pop is instigated, the view stack service needs to be aware of it so that it can keep the page stack data in sync.

Finally, here is the view implementation. This is the part that is most specific to my scenario, because it is a Xamarin.Forms implementation:

publicsealedclassMainView:NavigationPage,IView{privatereadonlyISchedulerbackgroundScheduler;privatereadonlyISchedulermainScheduler;privatereadonlyIViewLocatorviewLocator;privatereadonlyIObservable<IPageViewModel>pagePopped;publicMainView(ISchedulerbackgroundScheduler,ISchedulermainScheduler,IViewLocatorviewLocator){Ensure.ArgumentNotNull(backgroundScheduler,nameof(backgroundScheduler));Ensure.ArgumentNotNull(mainScheduler,nameof(mainScheduler));Ensure.ArgumentNotNull(viewLocator,nameof(viewLocator));this.backgroundScheduler=backgroundScheduler;this.mainScheduler=mainScheduler;this.viewLocator=viewLocator;this.pagePopped=Observable.FromEventPattern<NavigationEventArgs>(x=>this.Popped+=x,x=>this.Popped-=x).Select(ep=>ep.EventArgs.Page.BindingContextasIPageViewModel).WhereNotNull();}publicIObservable<IPageViewModel>PagePopped=>this.pagePopped;publicIObservable<Unit>PushModal(IModalViewModelmodalViewModel,stringcontract){Ensure.ArgumentNotNull(modalViewModel,nameof(modalViewModel));returnObservable.Start(()=>{varpage=this.LocatePageFor(modalViewModel,contract);this.SetPageTitle(page,modalViewModel.Id);returnpage;},this.backgroundScheduler).ObserveOn(this.mainScheduler).SelectMany(page=>this.Navigation.PushModalAsync(page).ToObservable());}publicIObservable<Unit>PopModal()=>this.Navigation.PopModalAsync().ToObservable().ToSignal()// XF completes the pop operation on a background thread :/.ObserveOn(this.mainScheduler);publicIObservable<Unit>PushPage(IPageViewModelpageViewModel,stringcontract,boolresetStack,boolanimate){Ensure.ArgumentNotNull(pageViewModel,nameof(pageViewModel));// If we don't have a root page yet, be sure we create one and assign one immediately because otherwise we'll get an exception.// Otherwise, create it off the main thread to improve responsiveness and perceived performance.varhasRoot=this.Navigation.NavigationStack.Count>0;varmainScheduler=hasRoot?this.mainScheduler:CurrentThreadScheduler.Instance;varbackgroundScheduler=hasRoot?this.backgroundScheduler:CurrentThreadScheduler.Instance;returnObservable.Start(()=>{varpage=this.LocatePageFor(pageViewModel,contract);this.SetPageTitle(page,pageViewModel.Id);returnpage;},backgroundScheduler).ObserveOn(mainScheduler).SelectMany(page=>{if(resetStack){if(this.Navigation.NavigationStack.Count==0){returnthis.Navigation.PushAsync(page,animated:false).ToObservable();}else{// XF does not allow us to pop to a new root page. Instead, we need to inject the new root page and then pop to it.this.Navigation.InsertPageBefore(page,this.Navigation.NavigationStack[0]);returnthis.Navigation.PopToRootAsync(animated:false).ToObservable();}}else{returnthis.Navigation.PushAsync(page,animate).ToObservable();}});}publicIObservable<Unit>PopPage(boolanimate)=>this.Navigation.PopAsync(animate).ToObservable().ToSignal()// XF completes the pop operation on a background thread :/.ObserveOn(this.mainScheduler);privatePageLocatePageFor(objectviewModel,stringcontract){Ensure.ArgumentNotNull(viewModel,nameof(viewModel));varview=viewLocator.ResolveView(viewModel,contract);varviewFor=viewasIViewFor;varpage=viewasPage;if(view==null){thrownewInvalidOperationException($"No view could be located for type '{viewModel.GetType().FullName}', contract '{contract}'. Be sure Splat has an appropriate registration.");}if(viewFor==null){thrownewInvalidOperationException($"Resolved view '{view.GetType().FullName}' for type '{viewModel.GetType().FullName}', contract '{contract}' does not implement IViewFor.");}if(page==null){thrownewInvalidOperationException($"Resolved view '{view.GetType().FullName}' for type '{viewModel.GetType().FullName}', contract '{contract}' is not a Page.");}viewFor.ViewModel=viewModel;returnpage;}privatevoidSetPageTitle(Pagepage,stringresourceKey){vartitle=Localize.GetString(resourceKey);page.Title=title;}}

Crucially, our view extends NavigationPage, since that is the page type that gives us navigation capabilities in Xamarin.Forms. From there, we must also implement IView.

Perhaps the trickiest aspect of this code is in dealing with Xamarin.Forms’ idiosynchrasies. Specifically, a root page is required before any attempt is made to realize the view on-screen. This wouldn’t be a problem except that I also want to create views off the main thread to increase perceived performance. If we create views on a background thread, that leaves the UI thread free to show a spinner or the like, thereby mitigating the risk of nasty lags as the user switches between views. However, if we create the very first page off the UI thread, we have a race condition. Xamarin.Forms expects there to be a root page when it first attempts to render the view, but our background thread may still be in the process of creating it. Therefore, all views are created on a background thread except the root view.

Another annoyance is in dealing with resetting the stack. Xamarin.Forms has the ability to pop to the root view, but not to completely supplant the root view with another. To that end, we have to get a bit tricky by inserting our new root view and popping to that instead.

Other than those warts, the code is quite clean.

Notice the SetPageTitle method, which uses the Id of the page (or modal) as a key with which to look up a resource to use as the title. The Localize class is outside the scope of this post, but it’s exactly what you’d expect. You can always replace it with something else. If your application isn’t localized, you could even just use the actual titles as the IDs, though I wouldn’t recommend it.