如何在 RxJava2 中停止观察一个 Observable 而不将其处置?

huangapple go评论57阅读模式
英文:

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

问题

我在RxJava2中遇到了一个不寻常的问题。

基本上,我们有以下场景:

  • 用户拍照,然后通过按下“下一步”开始网络请求
  • 网络请求完成后,将执行ViewModel中的一个方法,该方法会触发UI操作
  • 用户随时可以按返回按钮,这应该重新启动流程,即使先前的照片已成功上传,也不应触发任何操作。

通常情况下,我会将所有的代码放在CompositeDisposable中,并根据情况调用clear()或dispose()。这样在用户按下返回按钮后,会停止观察已上传的照片

然而,在这种情况下,我不能调用clear()或dispose(),因为这会终止网络请求!照片通常为1-2 MB,调用dispose()会终止网络请求...
我如何停止观察先前的流并只观察未来的上传,而不终止先前的上传?

我知道应该有一种方法来通知我的可观察对象,表明用户按下了返回按钮,但是我所有的尝试似乎都有些巧妙而不够清晰。我想学习正确处理这种情况的方法。

英文:

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 request! 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.

答案1

得分: 1

在我看来,正确的方法是使用 takeUntil,这样您可以取消当前的上传操作,并在那一点上完成它。然后,您需要使用 repeat 来重新订阅以进行未来的上传操作。

类似这样的代码示例:

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

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()

huangapple
  • 本文由 发表于 2020年5月4日 00:53:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61578296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定