Using Android LiveData I'd like to be able to unregister and register many BroadcastReceiver
s in the onInactive()
and onActive()
call backs. So I want to do something like this:
public class BroadcastRecieverLiveData extends LiveData<BroadCastReciever> {
private BroadcastReciever reciever;
private Context context;
public BroadcastRecieverLiveData(Context context) {
this.context = context;
}
@Override
protected void onActive() {
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
reciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
};
registerReceiver(reciever, filter);
}
@Override
protected void onInactive() {
if (reciever != null) {
context.unregisterReceiver(reciever);
}
}
}
I was thinking this could be a design pattern to be clean up of code instead of relaying on onDestroy
. What are your thoughts on using LiveData this way? There is an example of using it here