简体   繁体   中英

How can I stop observing an observable without disposing it in RxJava2?

I have an unusual issue with RxJava2.

Basically we have a following scenario:

  • User takes a picture and by pressing next starts network request
  • After network request is finished a method in ViewModel is executed, which triggers UI action
  • User at any time can press back button , which should restart a flow and even if previous photo is uploaded successfully it should not trigger any actions.

Now typically I would put all my code in CompositeDisposable and call clear() or dispose () depending on my case. This will stop observation of uploaded photo after uses presses back button.

However, I can't call clear() or dispose() in this case, because it would terminate network reques t. Photo is usually 1-2 mb and by calling dispose it would terminate network request.., How can I stop observing previous flow and observe only future uploads? without terminating previous upload?

I know that there is should be some kind of way to notify my observable that user pressed a back button, but all my attempts seems hacky and not clean. I would like to learn a correct way of handling such case.

The correct way in my opinion is to use takeUntil so you get to cancel the current upload and it completes at that point. Then you need to use repeat to re-subscribe again for future uploads.

Something like this:

compositeDisposable += nextButtonClicked
        .firstOrError()
        .flatMapCompletable {
          networkUpload.takeUntil(backButtonClicked).ignoreElements()
        }.repeat().subscribe()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM