【发布时间】:2020-08-23 07:24:23
【问题描述】:
我已经创建了 FragmentA 并在 onViewCreated() 中初始化了 ViewModel。我用同样的方法附加了观察者。
在 FragmentA 中,我正在进行 API 调用,在 API 调用成功后,我将 FragmentA 替换为 FragmentB 和 addToBackStack。
现在真正的问题是当我按下 FragmentB 中的返回按钮时,返回堆栈中的 FragmentA 被调用,但又立即被 FragmentB 替换。
class FragmentA : Fragment(){
private var viewModel: TrackingViewModel?=null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewModel()
attachObservers()
}
private fun initViewModel(){
viewModel = ViewModelProvider(requireActivity()).get(TrackingViewModel::class.java)
}
private fun attachObservers() {
viewModel?.mResult?.observe(viewLifecycleOwner, {
it?.let { resource ->
parseResource(resource)
}
})
}
//Called this method on Button CLick in UI
private fun validate(data:String){
viewModel?.coroutineSearch(data)
}
private fun parseResource(resource: Resource<GetsApiResponse>) {
when (resource.status) {
Status.SUCCESS -> {
showLoading(false)
//replaceFragmentWithBackStack is an Extension function
replaceFragmentWithBackStack(FragmentB(), R.id.container)
}
Status.ERROR -> {
showLoading(false)
infoError(resource.responseCode)
}
Status.EXCEPTION -> {
showLoading(false)
infoException()
}
Status.LOADING -> {
showLoading(true)
}
}
}
}
【问题讨论】:
-
你使用导航组件吗?
-
@A.R.B.N 我没有使用导航组件。
标签: android fragment viewmodel