无法在后台线程上调用 setValue

Gre*_*r A 2 android kotlin kotlin-coroutines

有人可以告诉我我做错了什么吗

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())
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

调用以下方法时会抛出错误

_torrents.value = jsonString
Run Code Online (Sandbox Code Playgroud)

sno*_*lax 14

您应该使用postValue

SetValue不适用于后台进程。

信息

该方法(setValue)必须从主线程调用。如果需要从后台线程设置值,可以使用 postValue(Object)