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

Why Socket Io how update my UI Jetpack with mutableList?

I try to update my Jetpack UI when socket event give me data but my list did not change after socket event function ended

@HiltViewModel
class MyModelViewModel @Inject constructor(
    private val repository: Repository,
    private val socket: Socket
) : ViewModel() {

    init {
        getDataList()
    }

    var myModelList: MutableList<MyModel> = mutableListOf()

    private fun getDataList() {
        socket.connect()
        socket.on("EVENT_NAME") { arg ->
             myModelList=
                Gson().fromJson(arg[0].toString(), Array<MyModel>::class.java)
                    .toList() as MutableList<MyModel>
        }
  }
} 

And I update my UI like that

@SuppressLint("UnrememberedMutableState")
@Composable
fun TokenList(
    viewModel: MyModelViewModel = hiltViewModel()
) {
    val myModelListState by mutableStateOf(viewModel.myModelList)

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

>Solution :

In Compose a view can only be updated by changes of a mutable state. You need to use it inside your view model, instead of your view.

If you don’t need to add/remove single items from your list in future, you can use mutableStateOf:

var myModelList by mutableStateOf<List<MyModel>>(listOf())
//..
myModelList = Gson().fromJson(arg[0].toString(), Array<MyModel>::class.java).toList()

Otherwise, you can use mutableStateListOf:

val myModelList = mutableStateListOf<MyModel>()
//..
myModelList.addAll(Gson().fromJson(arg[0].toString(), Array<MyModel>::class.java))

In both cases, you don’t need mutableStateOf in your view, you can access myModelList directly.

Also, suppressing "UnrememberedMutableState" is something that should never be done, because using a changeable state without remember does not allow it to be remembered between recompositions, which makes it useless.

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