Observable which does not pass anything in onNext()

前端 未结 6 951
猫巷女王i
猫巷女王i 2021-02-02 06:52

I would need an Observable, for example to provide a system clock, which does not need to pass anything in onNext(). I couldn\'t find a signature that would allow me to do that.

6条回答
  •  太阳男子
    2021-02-02 07:16

    You don't need to call onNext if your Observable doesn't emit anything. You could use Void in your signature and do something like

    Observable o = Observable.create(new Observable.OnSubscribe() {
        @Override
        public void call(Subscriber subscriber) {
            // Do the work and call onCompleted when you done,
            // no need to call onNext if you have nothing to emit
            subscriber.onCompleted();
        }
    });
    
    o.subscribe(new OnCompletedObserver() {
        @Override
        public void onCompleted() {
            System.out.println("onCompleted");
        }
    
        @Override
        public void onError(Throwable e) {
            System.out.println("onError " + e.getMessage());
        }
    });
    

    You can define an OnCompletedObserver to simplify your Observer callback so that you don't have to override the onNext since you don't need it.

    public abstract class OnCompletedObserver implements Observer {
        @Override
        public void onNext(T o) {
    
        }
    }
    

    If I've understood what you're asking then this should do the trick.

提交回复
热议问题