Search code examples
androidbroadcastreceiverrx-java2subject-observer

Which one is preferable : Rx-Subject or Android BroadcastReceiver


I have following project in Github : https://github.com/alirezaeiii/ExoPlayer-Service where I play music using ExoPlayer from Assets.

When I click on Play/Pause button, I send a broadcast to Play/Pause ExoPlayer :

public void playPauseClick(View view) {
        isPlaying = !isPlaying;
        Intent intent = new Intent(STR_RECEIVER_SERVICE);
        intent.putExtra(IS_PLAYING, isPlaying);
        sendBroadcast(intent);
}

And here is my BroadcastReceiver which registered in my Android Service :

private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isPlaying = intent.getBooleanExtra(IS_PLAYING, false);
            mExoPlayer.setPlayWhenReady(isPlaying);
        }
    };

Another approach is using Rx-Subject. So in my Activity I use onNext() to Play/pause the ExoPlayer :

public void playPauseClick(View view) {
     isPlaying = !isPlaying;
     PLAYING_SUBJECT.onNext(isPlaying);
}

And in the Service I have following Disposable, which I dispose in onDestroy() :

public static final Subject<Boolean> PLAYING_SUBJECT = PublishSubject.create();

private final Disposable mPlayingDisposable = PLAYING_SUBJECT.subscribe(new Consumer<Boolean>() {
        @Override
        public void accept(Boolean isPlaying) {
            mExoPlayer.setPlayWhenReady(isPlaying);
        }
    });

both broadcast and Rx-Subject works as expected, but in your point of view which one is preferable upon another and why in my case?


Solution

  • Never use IPC (inter-process communication) for communications within your own process. Not only is it wasteful of resources, but it introduces security problems. For example, any app can send that broadcast to you.

    Whether you use RxJava or something else (Kotlin's SharedFlow, LiveData, etc.) that is in-process is up to you. But, please, do not use system broadcasts for in-process communications.