1

This is rather an am I doing this correctly question.

I have a MediaPlayer service to play audio. Due to few requirements, it is a callback hell with too many listeners.

For example: Currently, I have an audio route button to toggle audio routing between earpiece and loud speaker. I currently use bound service and call reRouteAudio() method on on service from my UI and listen to callback for the result so I can change the icon and action on the route button.

To test if it will be cleaner, I have changed above flow to LiveData implementation.

I have created a singleton called PlayerServiceLiveData and following methods

public void updateAudioRoute(AudioRoute audioRoute) {
    this.audioRoute.postValue(audioRoute);
}

public LiveData<AudioRoute> getAudioRoute() {
    return audioRoute;
}

I observe this in my activity with

PlayerServiceLiveData.getInstance().getAudioRoute().observe(this, new Observer<AudioRoute>() {
        @Override
        public void onChanged(AudioRoute audioRoute) {
            if (App.DEBUG) {
                AppHelper.Log(TAG, "AudioRoute updated to: " + audioRoute);
            }
        }
    });

An update it from the Service with

PlayerServiceLiveData.getInstance().updateAudioRoute(currentAudioRoute);

It seems to work fine and looks a lot cleaner.

So, my question is: Is this an OK/Healthy way? Am I right for thinking that this is the way to go since Google also deprecating LocalBroadcastManager

nLL
  • 5,662
  • 11
  • 52
  • 87
  • If your concern is stuff like memory leaks, assuming that an `AudioRoute` is cheap, this should be OK. Someday, if you get into dependency injection, you should inject this rather than have a manually-created singleton. Until then, I wonder if there is some other singleton (e.g., a repository) that might hold a `LiveData`, rather than making the `LiveData` itself a singleton. – CommonsWare Dec 23 '18 at 22:21
  • Thank you. I have just noticed that LiveData value is retained. It looks like I need to use something like SingleLiveEvent – nLL Dec 24 '18 at 12:23

0 Answers0