Search code examples
androidrx-java2

Completable.fromAction not executing the code in rjava2


 Completable.fromAction(() -> startRecording())
 .subscribeOn(Schedulers.io())
 .subscribe(() -> {
        boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
        if (startSuccess) {
            updateView();
            startRepeatingTask();
        }
    },throwable -> {
        Logger.info("Record failed with exception" + throwable);
    }).dispose();

I am trying to execute code in background using Completable.fromAction but it is not executing the code if I use subscribeOn(Schedulers.io()).

if I remove subscribeOn(Schedulers.io()), it is executing the code in main thread. I want to executing the code in background thread.


Solution

  • People have already highlighted the problem with your code in the comments - you call dispose() on the Disposable that your Completable returns immediately. This means you cancel your Completable before it has even started. Alter your code to store your Disposable in an instance variable, and call dispose() only when you are no longer interested in receiving it completing. This usually happens in a lifecycle callback like onPause or onStop. For example:

    public class SomeActivity extends Activity {
    
        private final CompositeDisposable disposables = new CompositeDisposable(); 
    
        //...
    
        disposables.add(Completable.fromAction(() -> startRecording())
            .subscribeOn(Schedulers.io()) //Note: `updateView` implies UI work. Should you also have `observeOn(AndroidSchedulers.mainThread)?
            .subscribe(() -> {
                boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
                if (startSuccess) {
                    updateView();
                    startRepeatingTask();
                }
            }, throwable -> {
            Logger.info("Record failed with exception" + throwable);
            }));
    
         //Later, in some other lifeycle callback when you no longer care about updates...
         disposables.clear();