Impossible d'appeler setValue sur un thread d'arrière-plan [duplicate]

Sep 16 2020

Quelqu'un peut-il me dire ce que je fais mal

private fun getTorrentsSocketIO() {
    coroutineScope.launch {
        try {
            val socket = IO.socket("...")
            socket.on("torrents") {
                val jsonString = it.toList() as List<Torrent>
                _torrents.value = jsonString
            }
            socket.connect()
        } catch (t: Throwable) {
            Log.i("LIST_VIEW_MODEL", t.message.toString())
        }
    }
}

Une erreur est générée lorsque le suivant est appelé

_torrents.value = jsonString

Réponses

2 snorlax Sep 16 2020 at 18:19

Vous devez utiliser le postValue .

SetValue ne fonctionnera pas pour les processus d'arrière-plan.

Info

Cette méthode (setValue) doit être appelée à partir du thread principal. Si vous avez besoin de définir une valeur à partir d'un thread d'arrière-plan, vous pouvez utiliser postValue (Object)