Jetpack撰写惰性列未与列表重新组合



我有一个通过Stateflow存储在Viewmodel中的列表。

class FirstSettingViewModel : ViewModel() {
     private val _mRoomList = MutableStateFlow<List<InitRoom>>(mutableListOf())
     val mRoomList: StateFlow<List<InitRoom>> = _mRoomList
    
     ...

我通过collectAsState()观察流量。LazyColumn由可点击的方框组成。

val roomList = mViewModel.mRoomList.collectAsState()
Dialog {
    ...
    LazyColumn(...) {
        items(roomList.value, key = { room -> room.room_seq}) { room ->
          
           Box(Modifier.clickable {
              **mViewModel.selectItem(room)**
           }) {...}
       }
    }
}

当点击事件发生时,viewModel通过复制列表改变'isSelected'值,如下所示。

fun selectItem(room: InitRoom) = viewModelScope.launch(Dispatchers.IO) {
    try {
        val cpy = mutableListOf<InitRoom>()
        mRoomList.value.forEach {
            cpy.add(it.copy())
        }
        cpy.forEach {
            it.isSelected = it.room_seq == room.room_seq
        }
        _mRoomList.emit(cpy)
    } catch (e: Exception) {
        ErrorController.showError(e)
    }
}

当在基于xml的视图和ListAdapter中,这段代码将工作得很好,但在上面的组合代码中,它似乎根本没有重组LazyColumn。我能做些什么re-composeLazyColumn ?

SnapshotStateList代替普通的List

改变这一现状,

private val _mRoomList = MutableStateFlow<List<InitRoom>>(mutableListOf())
val mRoomList: StateFlow<List<InitRoom>> = _mRoomList

private val _mRoomList = MutableStateFlow<SnapshotStateList<InitRoom>>(mutableStateListOf())
val mRoomList: StateFlow<SnapshotStateList<InitRoom>> = _mRoomList

相关内容

  • 没有找到相关文章

最新更新