前提:我已经阅读并试用了其他帖子中提出的所有解决方案,其中其他用户也有相同的例外。
我在我的应用程序的onCreate中启动了一条线程
open class App : Application() {
override fun onCreate() {
Thread {
...
}.start()
}
}在某个时候,总是在线程中,我有一个类希望使用'by Delegates.observable‘实现一个可观察的变量
class MyService{
var myVariable: String by Delegates.observable("default value") { _, oldValue, newValue ->
onVariableChanged?.invoke(oldValue, newValue)
}
var onVariableChanged: ((String, String) -> Unit)? = null
fun doSomething(){
myVariable = "result"
// ---- I also tried the 2 solutions commented below ----
//
// val handler = Handler(getMainLooper())
// handler.post {myVariable = "result"}
// GlobalScope.launch {
// withContext(Dispatchers.Main){
// myVariable = "result"
// }
// }
}
}现在我需要在ViewModel中能够观察到应该在线程中更新的变量
class MyViewModel(application: Application) : AndroidViewModel(application) {
// ---- I also tried with couroutines --------
// private val viewModelJob = SupervisorJob()
// private val viewModelScope = CoroutineScope(viewModelJob + Dispatchers.Main)
init {
// viewModelScope.launch {
// onVariableThreadChanged()
// }
onVariableThreadChanged()
}
private fun onVariableThreadChanged(){
myServiceInstance.onVariableChanged = {oldValue , newValue ->
.....
}
}
}在读取日志文件时,我看到在线程方法中,我试图分配值。
myVariable = "result"的变量'by Delegates.observable‘给了我一个例外
“只有创建视图层次结构的原始线程才能触摸其视图。”
发布于 2020-06-22 07:37:33
我通过将委托放入couroutineScope (Dispatchers.Main) .launch {.}并将活动中的viewModel代码移动到runOnUiThread {..}方法来解决问题。
进入MyService
CoroutineScope(Dispatchers.Main).launch {
myVariable = "result"
}进入MyActivity
runOnUiThread(
myServiceInstance.onVariableChanged = {oldValue , newValue ->
.....
}
)https://stackoverflow.com/questions/62446987
复制相似问题