In my app, I need to add/remove/update data in my db from a BroadcastReceiver. I am wondering what are the best practices regarding this. Since the onReceive is called on the main thread, I need a way to run the queries on a worker thread and on completion I need the response in the onReceive method.
For this, I used a simple Observer pattern like this.
public class NetworkChangeReceiver extends BroadcastReceiver implements IDbUpdateListener{
private MyRepository repo;
private Application application;
@Override
public void onReceive(Context context, Intent intent) {
//Some conditions
//Initializing and setting listener for repo
respo = new MyRepository(this); //this is the listener interface
repo.getAllContents();
}
}
}
//Interface method implemented
@Override
public void onDbUpdate(Content content) {
//Do something with the data
}
}
I passed the listener to the repo where I call the onDbUpdate() method on the listener and thereby get the response in the receiver.
If it was an activity/fragment instead of a broadcast receiver, I would have simply used a viewModel with live data as the observable and in my activity, I would observe the viewmodel for changes like this
mViewModel.getAllContent().observe(this, new Observer<List<Content>>() {
@Override
public void onChanged(@Nullable final List<Content> contents) {
// Do something
}
});
Is my approach ok or is there an obvious better way of achieving this in BroadcastReceiver? Thanks!!