Skip to content

Instantly share code, notes, and snippets.

@aritchie
Created July 11, 2016 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aritchie/41c9faba48de5ce25177b1cb11157623 to your computer and use it in GitHub Desktop.
Save aritchie/41c9faba48de5ce25177b1cb11157623 to your computer and use it in GitHub Desktop.
Android Broadcast Receivers to RX Observables
public static class AndroidObservables
{
public static IObservable<Intent> WhenIntentReceived(string intentAction)
{
return Observable.Create<Intent>(ob =>
{
var filter = new IntentFilter();
filter.AddAction(intentAction);
var receiver = new ObservableBroadcastReceiver
{
OnEvent = ob.OnNext
};
Application.Context.RegisterReceiver(receiver, filter);
return () => Application.Context.UnregisterReceiver(receiver);
});
}
}
public class ObservableBroadcastReceiver : BroadcastReceiver
{
public Action<Intent> OnEvent { get; set; }
public override void OnReceive(Context context, Intent intent)
{
this.OnEvent?.Invoke(intent);
}
}
// EXAMPLES
public static IObservable<BluetoothDevice> WhenDeviceNameChanged()
{
return WhenDeviceEventReceived(BluetoothDevice.ActionNameChanged);
}
public static IObservable<BluetoothDevice> WhenDeviceEventReceived(string action)
{
return AndroidObservables
.WhenIntentReceived(action)
.Select(intent =>
{
var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
return device;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment