我只需要提取数据一次,并避免在屏幕旋转时提取它。
我的片段:
private var _binding: FragmentTopArticlesBinding? = null
private val binding get() = _binding!!
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentTopArticlesBinding.inflate(inflater, container, false)
getTopArticles()
return binding.root
}
状态观察功能:
private fun getTopArticles() {
var sortedList = emptyList<Article>()
val adapter = ArticleAdapter(
onArticleClicked = { title ->
Toast.makeText(context, title, Toast.LENGTH_SHORT).show()
}
)
binding.recyclerViewTop.layoutManager = LinearLayoutManager(context)
binding.recyclerViewTop.adapter = adapter
lifecycleScope.launch {
viewModel.stateUI.collect { it ->
when (it) {
is StateUI.Success -> {
it.articles.collect { articles ->
if (articles.isNotEmpty()) {
observeArticles(sharedViewModel, articles, adapter)
取数函数:
private suspend fun observeArticles(
sharedViewModel: SharedViewModel,
articles: List<Article>,
adapter: ArticleAdapter
) {
binding.progressBar.visibility = View.GONE
sharedViewModel.sortState.collect { sortState ->
val sortedList = when (sortState) {
SortOrderState.Ascending -> {
sharedViewModel.sortArticles(articles)
}
SortOrderState.Descening -> {
sharedViewModel.sortArticles(articles)
}
}
adapter.submitList(sortedList)
binding.recyclerViewTop.postDelayed({
binding.recyclerViewTop.scrollToPosition(0)
}, 1000)
}
}
我的任务是在用户点击菜单项排序(升序或降序)时获取和排序2个片段上的数据。问题是当我旋转屏幕时,这些函数获取数据,但我只想在片段中第一次来时做一次。
我删除了这行代码:
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
因为我不能使用scrollToPosition。
- 编辑:**
视图模型:
private val _cacheArticle = MutableStateFlow(emptyList<Article>())
val cacheArticle = _cacheArticle.asStateFlow()
init {
viewModelScope.launch {
if(cacheArticle.value.isEmpty()){
val observeTopArticles = articleRepository.getTopArticles()
_cacheArticle.value = observeTopArticles
_stateUI.value = StateUI.Success(articles = observeTopArticles)
Log.d(TAG, ": PULL")
} else
{
Log.d(TAG, ": CACHE1")
_stateUI.value = StateUI.Success(articles = _cacheArticle.value)
}
}
1条答案
按热度按时间u5rb5r591#
您可以像这样在Fragment中获取数据
在屏幕旋转和片段重新创建之后,
savedInstanceState
将不为空,因此该方法将仅在第一次创建片段时调用一次。