使用导航组件ViewModel
和LiveData
时遇到问题。
我在MatchDetailFragment
中观察到服务器的响应,并且在收到服务器的响应后,我的MatchDetailFragment
得到了有关观察到的实时数据变化的通知,我导航到ScoreFragment
,但是当我导航时返回到MatchDetailFragment
,观察到的响应将再次得到通知,并尝试再次导航到MatchDetailFragment
,并且由于findNavController()
的目的地仍为MatchDetailFragment
并试图转到nextDestination
中未定义的MatchDetailFragment
现在首先我的LiveData
应该在我仅按Backstack时得到通知,因为我需要根据响应移至片段B
这是合适的代码
MatchDetailFragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding: FragmentMatchDetailBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_match_detail, container, false)
matchDetailViewModel = ViewModelProviders.of(this).get(MatchDetailViewModel::class.java)
binding.matchDetailViewModel = matchDetailViewModel
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
matchDetailViewModel.matchDetail.value = args.selctedMatch
matchDetailViewModel.newMatchSetResponse.observe(viewLifecycleOwner, Observer { resource ->
when (resource) {
is Resource.Loading -> {
showLoading()
}
is Resource.Success -> {
hideLoading()
with(resource.data) {
if (this.body() != null) {
val nextDestination = MatchDetailFragmentDirections.nextAction(this.body()!!, args.selctedMatch)
findNavController().navigate(nextDestination)
} else {
root.showSnackbar(this.message(), Snackbar.LENGTH_LONG)
}
}
}
is Resource.Failure -> {
hideLoading()
root.showSnackbar("Error occurred", Snackbar.LENGTH_LONG)
}
}
})
}
ScoreFragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding: FragmentScoreBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_score, container, false)
binding.match = args.matchDetail
binding.setResponse = args.matchSetResponse
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
scoreViewModel = ViewModelProviders.of(this).get(ScoreViewModel::class.java)
}