ReactiveUI: Binding to an Android service the reactive way

ReactiveUI: Binding to an Android service the reactive way

ReactiveUI is a MVVM framework that takes full advantage of the Reactive Extensions for .NET (Rx.NET) where everything is a stream.

Together with Xamarin it’s possible to use it in the development of Android applications. When on this platform, you may need to bind to a service. Binding is an asynchronous operation and, when using the Android API, the operation is based on callbacks. Xamarin simply wraps this process to .NET and not having anonymous classes in C# makes binding a bit of a mess.

The ReactiveUI includes Context.ServiceBound() extension methods that return an IObservable<IBinder>.

public static IObservable<IBinder> ServiceBound (
this Context context, Intent intent, Bind flags = Bind.None)

public static IObservable<TBinder> ServiceBound<TBinder> (
this Context context, Intent intent, Bind flags = Bind.None)
where TBinder: class, IBinder

Binding now only requires a couple of lines of code:

var intent = new Intent(context, typeof(DemoService));
var bind = context.ServiceBound (intent, Bind.AutoCreate);

Notice that unlike BindService() you don’t have to pass in an IServiceConnection, it is managed internally by the Observable. The connection is unbound automatically when the Observable subscription is disposed.

The second extension method lets you specify the binder type as the generics argument. This lets you access the public API of the binder.

The returned value is an IObservable so you can subscribe to it. You can use it together with Reactive Extensions and ReactiveUI to develop reactive apps.

Please note that the observable can push more than one value. The service connection can be lost but recovered later. This results in a null value pushed by the observable that may be followed by a new binder reference (if connection is restored).

Featured image: “Electrifying sunset” by aalmada

Advertisements