Created
July 11, 2016 02:26
-
-
Save aritchie/41c9faba48de5ce25177b1cb11157623 to your computer and use it in GitHub Desktop.
Android Broadcast Receivers to RX Observables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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