LiveData vs Handler and LocalBroadcast

user1244932 :

I have old Android/java code, that contains two derives from IntentService, and these services not run in separate processes.

The question is about the way to return result from these IntentService.

One service return result by using Handler + Runnable, to run code in main loop:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        MyApplication.get().setFoo(someThing);
    }
});

the other one is uses LocalBroadcastManager.getInstance(this).sendBroadcast(in); to send message to Activity, and Activity subscribe via BroadcastReceiver on message in onResume, and unsubscribe in onPause.

Am I right, and in both case it is possible to use LiveData to simplify things?

IntentService should create LiveData and who want result should observe it, and when new data arrives IntentService should call postValue, or may be there are some reefs to prevent usage of LiveData here?

Vasiliy :

I think that LiveData will not help you in sending any data from Service to other components.

The problem with communication from any Service to other components is that you don't usually obtain a direct reference to the Service, therefore you can't directly "subscribe" to notifications.

Theoretically, if the Service runs in the same process, you can bind it, obtain a reference to Service object and then directly perform subscription. However, this is often an overkill and I don't see this pattern being used widely.

In your examples, there are two communication mechanisms:

  1. Service reaches statically to Application object and sets some data. This is a communication through global state, and is generally considered an anti-pattern.
  2. Communication through LocalBroadcastManager

From the above two mechanisms, I would use only #2 and avoid #1 at all costs.

Back to LiveData.

In order to be able to get LiveData object from the Service you will need to have a reference to that Service. This is usually impossible unless you bind Service in the same process, or use some ugly hack that involves global state.

Therefore, usefulness of LiveData in this context is very limited.

By the way, while LocalBroadcastManager is alright, I find this mechanism too complicated and restricting. Therefore, if the Service runs in the same process, I prefer to use EventBus in order to communicate from Service to other components (or vice-versa).

An example of such a communication you can see in SQLite benchmarking application that I wrote several days ago. In this app, TestService posts status changes and test results to EventBus as sticky events, and TestActivity subscribes to those events.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=429877&siteId=1