在我的android应用中,我的网络操作时间很长。操作完成后,我需要更新我的用户界面。
因此,需要在后台线程中执行较长的操作。
摘要:
private val isShowProgressLiveData = MutableLiveData<Boolean>()
// launch a new coroutine in background and continue
GlobalScope.launch() {
try {
val executeOperations = OperationFactory.createExecuteTraderOperation(Trader.Operation.CREATE, base, quote)
val response: Response<Void> = executeOperations.await()
if (response.isSuccessful) {
isShowProgressLiveData.value = false
isForwardToTradersLiveData.value = true
} else {
Debug.w(TAG, "doClickStart_error")
}
} catch (e: Throwable) {
Debug.e(TAG, "doClickStart_network error: $e.message", e)
}
}
但我在
上遇到错误isShowProgressLiveData.value = false
错误消息:
java.lang.IllegalStateException: Cannot invoke setValue on a background thread
at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:461)
at androidx.lifecycle.LiveData.setValue(LiveData.java:304)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
at com.myoperation.AddTraderViewModel$doClickStart$3.invokeSuspend(AddTraderViewModel.kt:55)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
我需要在主线程中更新ui。那我该如何解决呢?
答案 0 :(得分:2)
您可以像withContext(Dispatchers.Main)
那样切换到主线程
当您启动协同程序时,将在Dispatchers.Default
上启动。最好是这样指定它:
GlobalScope.launch(Dispatchers.IO) {
try {
val executeOperations = OperationFactory.createExecuteTraderOperation(Trader.Operation.CREATE, base, quote)
val response: Response<Void> = executeOperations.await()
if (response.isSuccessful) {
withContext(Dispatchers.Main){ //switched to Main thread
isShowProgressLiveData.value = false
isForwardToTradersLiveData.value = true
}
} else {
Debug.w(TAG, "doClickStart_error")
}
} catch (e: Throwable) {
Debug.e(TAG, "doClickStart_network error: $e.message", e)
}
}
答案 1 :(得分:0)
当您尝试执行
时,您仍处于后台线程中isShowProgressLiveData.value = false
您可以执行以下操作:
GlobalScope.launch() {
try {
val executeOperations = OperationFactory.createExecuteTraderOperation(Trader.Operation.CREATE, base, quote)
val response: Response<Void> = executeOperations.await()
if (response.isSuccessful) {
YourActivity.runOnUiThread(object:Runnable() {
override fun run() {
isShowProgressLiveData.value = false
isForwardToTradersLiveData.value = true
}
}
} else {
Debug.w(TAG, "doClickStart_error")
}
} catch (e: Throwable) {
Debug.e(TAG, "doClickStart_network error: $e.message", e)
}
}