gpt4 book ai didi

android - fragment popbackstack 触发生命周期范围收集

转载 作者:行者123 更新时间:2023-12-04 12:22:02 25 4
gpt4 key购买 nike

情况
我提交数据setTripDeliver ,收集工作正常(触发加载,然后成功)。我按下一个按钮转到下一个 fragment B(使用 replace )。之后,我按下返回按钮(使用 popbackstack )。收集成功触发。
相关代码
这些代码位于 FragmentA.kt里面 onViewCreated .

private fun startLifeCycle() {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
collectTripDeliver()
}
launch {
collectTripReattempt()
}
}
}
}
这些代码何时在按钮上提交数据 setOnClickListener .
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.setTripDeliver(
verificationCode,
remark
)
}
收集流量的方法 collectTripReattempt()
private suspend fun collectTripReattempt() {
viewModel.tripReattempt.collect {
when (it) {
is Resource.Initialize -> {

}
is Resource.Loading -> {
Log.i("???","collectTripReattempt loading")
handleSaveEarly()
}
is Resource.Success -> {
val error = it.data?.error
if (error == null) {
Tools.showToast(requireContext(), "Success Reattempt")
Log.i("???","collectTripReattempt Success")

} else {
Tools.showToast(requireContext(), "$error")
}
handleSaveEnding()
}
is Resource.Error -> {
handleSaveEnding()
}
}
}
}
以下代码来自 ViewModel .
private val _tripDeliver =
MutableStateFlow<Resource<TripDeliverResponse>>(Resource.Initialize())
val tripDeliver: StateFlow<Resource<TripDeliverResponse>> = _tripDeliver
此方法调用存储库。
suspend fun setTripDeliver(
verificationCode: String?,
remark: String?
) {
_tripDeliver.value = Resource.Loading()
try {
val result = withContext(ioDispatcher) {
val tripDeliverParameter = DeliverParameter(
verificationCode,
remark
)
val response = appRepository.setTripDeliver(tripDeliverParameter)
Resource.getResponse { response }
}
_tripDeliver.value = result
} catch (e: Exception) {
when (e) {
is IOException -> _tripDeliver.value =
Resource.Error(messageInt = R.string.no_internet_connection)
else -> _tripDeliver.value =
Resource.Error("Trip Deliver Error: " + e.message)
}
}
}
日志猫
2021-07-09 19:56:10.946 7446-7446/com.package.app I/???: collectTripReattempt loading
2021-07-09 19:56:11.172 7446-7446/com.package.app I/???: collectTripReattempt Success
2021-07-09 19:56:17.703 7446-7446/com.package.app I/???: collectTripReattempt Success
如您所见,最后一个 Success在我按下返回按钮后再次调用 ( popbackstack)
问题
如何让它只触发一次?是我实现它的方式不对吗?先感谢您。

最佳答案

这不是您的实现的问题,这是因为 stateIn() 您的 viewModel 中使用了哪些将常规流量转换为 stateFlow如果根据您的代码 fragment 再次触发成功,那么为什么不触发加载?
根据文章,它显示 latest cached value当您离开屏幕并返回时,您会看到最新的缓存值。
资源:
https://medium.com/androiddevelopers/migrating-from-livedata-to-kotlins-flow-379292f419fbThe latest value will still be cached so that when the user comes back to it, the view will have some data immediately.

关于android - fragment popbackstack 触发生命周期范围收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68315415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com