Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jetpack compose lazy column not recomposing with list

I have a list which is stored inside a Viewmodel via Stateflow.

class FirstSettingViewModel : ViewModel() {

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

I observe the flow via collectAsState(). The LazyColumn consists of Boxes which can be clicked.

val roomList = mViewModel.mRoomList.collectAsState()

Dialog {

    ...

    LazyColumn(...) {

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

When a click event occurs, the viewModel changes the ‘isSelected’ value via a copied list like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }
}

When in an xml based view and a ListAdapter, this code will work well, but in the above compose code, it doesn’t seem to recompose the LazyColumn at all. What can I do to re-compose the LazyColumn?

>Solution :

Use a SnapshotStateList instead of an ordinary List

change this,

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

to this

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading