使用lifeCycleScope后的IllegalStateException



我使用了viewLifecycleOwner.lifecycleScope并尝试转换uploadPhotoStateFlowLiveData但我的应用程序仍然崩溃在解散loadingDialogFragment

LoadingDialogFragment.kt

class LoadingDialogFragment : DialogFragment() {
private lateinit var mBinding: DialogLoaderBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_TITLE, R.style.FullScreenDialogStyle)
isCancelable = false
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
mBinding = DialogLoaderBinding.inflate(inflater, container, false)
return mBinding.root
}
override fun show(manager: FragmentManager, tag: String?) {
///super.show(manager, tag)
try {
val ft: FragmentTransaction = manager.beginTransaction()
ft.add(this, tag).addToBackStack(null)
ft.commitAllowingStateLoss()
} catch (e: IllegalStateException) {
Log.e("IllegalStateException", "Exception", e)
}
}
}

ProfileFragment→onViewCreated

viewLifecycleOwner.lifecycleScope.launchWhenCreated {
mViewModel.uploadPhoto.collectLatest {
if (it.isLoading) {
loadingDialogFragment = LoadingDialogFragment()
loadingDialogFragment?.show(childFragmentManager, "loadingDialogFragment")
}
it.error?.let {
loadingDialogFragment?.dismiss() //crashed at here 
Toast.makeText(requireContext(), "No ", Toast.LENGTH_SHORT)
.show()
}
it.data?.let {
loadingDialogFragment?.dismiss() //crashed at here 
}
}
}

据我所知,当应用程序活动或片段处于onPause|onStop或onDestroy状态时,collectLatest代码不应该工作。

我也遇到过类似的问题

  • 我已经使用

    解决了这个问题
    viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
    // {code to collect from viewModel}
    }
    }
    

那么,你的代码看起来就像

viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED){
mViewModel.uploadPhoto.collectLatest {
if (it.isLoading) {
loadingDialogFragment = LoadingDialogFragment()
loadingDialogFragment?.show(childFragmentManager, "loadingDialogFragment")
}
it.error?.let {
loadingDialogFragment?.dismiss()
Toast.makeText(requireContext(), "No ", Toast.LENGTH_SHORT)
.show()
}
it.data?.let {
loadingDialogFragment?.dismiss()
}
}
}
}
  • 工作原理

repeatOnLifecycle是一个挂起函数。因此,它需要在协程中执行。repeatOnLifecycle挂起调用的协程,然后运行给定的挂起块,每次给定的生命周期达到目标状态或更高状态时,将该挂起块作为参数传递给新的协程。如果生命周期状态低于目标,则为该块启动的协程将被取消。最后,repeatOnLifecycle函数本身不会恢复调用协程,直到生命周期DESTROYED.

相关内容

  • 没有找到相关文章

最新更新