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.

For these applications you may need to bind to a service so you can access its functionality. 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 this implementation a bit of a mess.

The master branch for ReactiveUI version 7 (not yet released) includes a Context.ServiceBound() extension method that returns 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 returned value is an Observable so you can use async/await or use Rx.NET operators to filter and compose with other observables.

Featured image: “Electrifying sunset” by aalmada

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s