AppStateObservableOnSubscribe implements ObservableOnSubscribe<AppState> { @Override public void subscribe(@NonNull final ObservableEmitter<AppState> appStateEmitter) throws Exception { final AppStateListener appStateListener = new AppStateListener() { @Override public void onAppDidEnterForeground() { appStateEmitter.onNext(FOREGROUND); } @Override public void onAppDidEnterBackground() { appStateEmitter.onNext(BACKGROUND); } }; appStateEmitter.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { recognizer.removeListener(appStateListener); recognizer.stop(); } }); recognizer.addListener(appStateListener); recognizer.start(); } AppStateObservableOnSubscribe(@NonNull AppStateRecognizer recognizer); @Override void subscribe(@NonNull final ObservableEmitter<AppState> appStateEmitter);  }
@Test public void addsListenerAndStartsRecognitionOnSubscribe() { emitterObservable.subscribe(); verify(mockAppStateRecognizer).addListener(any(AppStateListener.class)); verify(mockAppStateRecognizer).start(); }
@Test public void removesListenerAndStopsRecognitionOnDispose() { emitterObservable.subscribe().dispose(); verify(mockAppStateRecognizer).removeListener(any(AppStateListener.class)); verify(mockAppStateRecognizer).stop(); }