How can I restart emitting, after disposing in RxJava 2?

Viewed 630

I dispose my observable in onPause(), and I would like to restart it in onResume(). How can I do that?

Here is my observable:

    Observable<ObdCommandResult> myObservable = Observable.create(new ObservableOnSubscribe<ObdCommandResult>() {
        @Override
        public void subscribe(ObservableEmitter<ObdCommandResult> e) throws Exception {
            ...
            socket.connect();

            new ObdResetCommand().run(socket.getInputStream(), socket.getOutputStream());
            new EchoOffCommand().run(socket.getInputStream(), socket.getOutputStream());
            new LineFeedOffCommand().run(socket.getInputStream(), socket.getOutputStream());
            new SelectProtocolCommand(ObdProtocols.AUTO).run(socket.getInputStream(), socket.getOutputStream());
            ObdCommandResult obdCommandResult = new ObdCommandResult();
            while (!Thread.currentThread().isInterrupted()) {
                for (int i = 1; i < 5; i++) {
                    try {
                        livedataObdCommandList.get(i-1).getCommand().run(socket.getInputStream(), socket.getOutputStream());
                        obdCommandResult.setId(i);
                        obdCommandResult.setValue(livedataObdCommandList.get(i-1).getCommand().getFormattedResult());
                        e.onNext(obdCommandResult);
                    }catch (UnsupportedCommandException uce) {
                    } catch (InterruptedException ie) {
                }
            }
        }
    });

...and my observer:

    Observer<ObdCommandResult> observer = new Observer<ObdCommandResult>() {
        @Override
        public void onNext(ObdCommandResult value) {
            switch (value.getId())  {
                case 1:
                    currentSpeed.setText(value.getValue());
                    break;
                case 2:
                    revCounter.setText(value.getValue());
                    break;
                case 3:
                    throttlePosition.setText(value.getValue());
                    break;
                case 4:
                    oilTemp.setText(value.getValue());
                    break;
                case 5:
                    fuelLevel.setText(value.getValue());
                    break;
                case 6:
                    engineCoolant.setText(value.getValue());
                    break;
            }
        }

    };

So I would like to dispose it, and restart when the user returns.

1 Answers

You can reuse the same observable and subscribe to it multiple times. Each call to subscribe() will result in a new subscription. (The body of the observable.create will not be executed, unless a subscription is made. Then, it will be executed for each subscription that is made.)

Related