0

I'm a beginner of RxJAVA. I want to assign an initialization job to another thread and announce me when it is completed so I can start to work. Because this Observable does not have any data to emit, so I use the Void type as discussed in this topic. But my Observer's onNext and onComplete will not work if I use Void type, I've tried to use String instead and it works fine. I want to ask should I use Void in this scenario or RxJAVA has some better way for this kind of requirement? Here is my code:

Observable.create(new ObservableOnSubscribe<Void>() {
  @Override
  public void subscribe(ObservableEmitter<Void> e) throws Exception {
    initialize();
    e.onNext(null);
    e.onComplete();
  }
}).subscribeOn(Schedulers.computation()).subscribe(new Observer<Void>() {
  @Override
  public void onSubscribe(Disposable d) {}

  @Override
  public void onComplete() {
    Log.d(TAG, "Test RxJAVA, onComplete");
  }

  @Override
  public void onError(Throwable e) {
    Log.d(TAG, "Test RxJAVA, onError");
  }

  @Override
  public void onNext(Void noData) {
    Log.d(TAG, "Test RxJAVA, onNext");
  }
});

Edit Edit the answer from @JohnWowUs. It works fine, thanks.

Completable.fromCallable(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    initialize();
  }
}).subscribeOn(Schedulers.computation())
  .subscribe(new CompletableObserver() {
      @Override
      public void onSubscribe(Disposable d) {}

      @Override
      public void onComplete() {
        Log.d(TAG, "Test RxJAVA, onComplete");
      }

      @Override
      public void onError(Throwable error) {
        Log.d(TAG, "Test RxJAVA, onError");
      }
});
Community
  • 1
  • 1
Josper
  • 167
  • 1
  • 1
  • 8

1 Answers1

2

RxJava no longer accepts null values. See here. You should be using a Completable in this case. Something like

Completable.fromCallable(new Callable<Void>() {
                            @Override
                            public Void call() throws Exception {
                                initialize();
                                return null;
                            })
           .subscribe(new CompletableObserver<Void>() {
                        @Override
                        void onSubscribe(Disposable d) {

                        }

                        @Override
                        void onComplete() {
                            Log.d(TAG, "Test RxJAVA, onComplete");
                        }

                        @Override
                        void onError(Throwable error) {
                            Log.d(TAG, "Test RxJAVA, onError");
                        });
JohnWowUs
  • 3,053
  • 1
  • 13
  • 20