Home > Blockchain >  Why Socket Io how update my UI Jetpack with mutableList?
Why Socket Io how update my UI Jetpack with mutableList?

Time:02-21

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)

CodePudding user response:

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.

  • Related