简体   繁体   English

如何避免在片段启动时每次触发loadIntent()

[英]How to avoid loadIntent() get fired each time on fragment start

When using mosby-mvi, 使用mosby-mvi时,

Following code works fine -- fired only once when fragment created. 以下代码工作正常-创建片段时仅触发一次。

override fun loadIntent(): Observable<Unit> {
    return Observable.just(Unit)
}

Following code works unexpected -- fired each time the activity wake up from background. 以下代码无法正常工作-每当活动从后台唤醒时就会触发。

override fun loadIntent(): Observable<Unit> {
    return Observable.just(Unit).mergeWith(RxView.clicks(error).map { Unit })
}

Why is that? 这是为什么?

That is RxJava's contract that Mosby respects. 那是Mosby遵守的RxJava的合同。

In the first example what happens is the following: 在第一个示例中,将发生以下情况:

override fun loadIntent(): Observable<Unit> {
  return Observable.just(Unit)
}

Then in the presenter presenter you do something like: 然后在演示者演示者中,您可以执行以下操作:

intent(YourView::loadIntent)

This basically subscribes to loadIntent() which is Observable.just(Unit) 这基本上订阅了loadIntent() ,它是Observable.just(Unit)

Then the following RxJava callbacks are triggered inside intent(YourView::loadIntent) : 然后在intent(YourView::loadIntent)内部触发以下RxJava回调:

--> onNext(Unit)
--> onComplete()

So your intent(YourView::loadIntent) reached the onComplete() state which means any future emissions will be just ignored (that is the RxJava contract). 因此,您的intent(YourView::loadIntent)达到了onComplete()状态,这意味着将来任何排放都将被忽略(即RxJava合同)。 So the "magic" why this intent only triggers is because in your presenter it reaches onComplete() . 因此,此意图仅触发的“魔术”是因为在您的演示者中,它达到了onComplete()

In the second example: 在第二个示例中:

override fun loadIntent(): Observable<Unit> {
    return Observable.just(Unit).mergeWith(RxView.clicks(error).map { Unit })
}

The thing to notice here mergeWith() operator. 这里要注意的事情mergeWith()运算符。 The "problem" here is that mergeWith() only completes (and calls onComplete() ) if both Observable.just(Unit) and RxView.clicks(error) individually reach onComplete . 这里的“问题”是,只有Observable.just(Unit)RxView.clicks(error)分别达到onCompletemergeWith()才完成(并调用onComplete() )。 While Observable.just(Unit) reaches onComplete() as already discussed in the previous code snipped, RxView.clicks(error) never reaches onComplete() and that is why mergeWith() never reaches onComplete() and that is why on Fragment recreation (like screen orientation change) this intent triggers again. 正如前面的代码RxView.clicks(error)已讨论的那样, Observable.just(Unit)到达onComplete()时, RxView.clicks(error)从未到达onComplete() ,这就是为什么mergeWith()永远不会到达onComplete() ,这就是在Fragment重新创建时的原因(例如更改屏幕方向),此意图会再次触发。

I would recommend to do the mergeWith() in your presenter and split it in two intents: loadIntnent() and retryLoadingOnErrorIntent() . 我建议在演示者中执行mergeWith()并将其分为两个意图: loadIntnent()retryLoadingOnErrorIntent()

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

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