简体   繁体   English

我怎样才能停止观察一个 observable 而不在 RxJava2 中处理它?

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

I have an unusual issue with RxJava2.我对 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网络请求完成后,ViewModel 中的一个方法被执行,触发 UI 动作
  • 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.现在通常我会将所有代码放入 CompositeDisposable 并根据我的情况调用 clear() 或 dispose () 。 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.但是,在这种情况下我不能调用 clear() 或 dispose(),因为它会终止网络请求 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?照片通常为 1-2 mb,通过调用 dispose 它将终止网络请求..,我怎样才能停止观察以前的流量而只观察未来的上传? 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.我知道应该有某种方式来通知我的 observable 用户按下了后退按钮,但我所有的尝试似乎都是 hacky 和不干净的。 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.我认为正确的方法是使用takeUntil ,这样你就可以取消当前的上传并在那时完成。 Then you need to use repeat to re-subscribe again for future uploads.然后您需要使用repeat再次重新订阅以供将来上传。

Something like this:像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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