如何将主要范围更改为Recyclerview Apapter中的另一个范围?

发布于 2025-01-28 14:54:09 字数 863 浏览 5 评论 0原文

这是我的代码适配器使用recyclerview。如何改进此代码以不使用主要范围,而是使用可以处理的范围? 我需要访问item.ID,这就是为什么我将其在不在viewModel/fragment中的适配器中使用的原因。

 _stateFlow.value = item.id

我在适配器中的代码

// define flowState
(...)
 val _stateFlow = MutableStateFlow(-1)
 val stateFlow = _stateFlow.asStateFlow()

// after every change of element
(...)
                CoroutineScope(Dispatchers.Main).launch {
                    stateFlow.collect { id ->
                        statusButtons.toggleVisibility(item.id == id)
                    }
                }

edit1答案以评论: 没有coroutine,当我的ID更改时,我将永远无法在状态流上使用。 我的动作就像我在单击下一个时需要触发以前单击的元素。

This is my code in adapter using recyclerView. How to improve this code to not use Main Scope, but to use scope that could be disposal?
I need to have access to get the item.id, that's why I use it in adapter not in viewmodel/fragment.

 _stateFlow.value = item.id

my code in adapter

// define flowState
(...)
 val _stateFlow = MutableStateFlow(-1)
 val stateFlow = _stateFlow.asStateFlow()

// after every change of element
(...)
                CoroutineScope(Dispatchers.Main).launch {
                    stateFlow.collect { id ->
                        statusButtons.toggleVisibility(item.id == id)
                    }
                }

EDIT1 answer for comment:
Without coroutine I can't use collect on stateFlow always when my id is changed.
My action is like I need to trigger element previously clicked when I click next one.

without coroutine I an't use collect

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文