gpt4 book ai didi

android - 在协程中切换到 UI 上下文

转载 作者:行者123 更新时间:2023-12-05 00:12:36 24 4
gpt4 key购买 nike

我是协程的新手,我想知道是否可以将下面的代码从协程范围 (GlobalScope) 切换到 UI 范围。我的问题是,协程启动体中的步骤必须在工作线程中执行,否则监听器通知必须在 ui 线程中执行,以避免在我的 Activity 代码中调用 runOnUiThread。

override suspend fun startRent(name: String, bikeMode: BikeMode, listener: StartRentListener) {
var bleDevice : RxBleDevice
val scanFilter: ScanFilter = ScanFilter.Builder().setDeviceName(name).build()
val scanSettings: ScanSettings = ScanSettings.Builder().build()

val job = GlobalScope.launch {
try {
bleDevice = rxBleClient.scanBleDevicesExt(rxBleClient, scanSettings, scanFilter)
val bleConnection = bleDevice.establishConnectionExt()
// write handshake
connectionManager.writeHandshake(bleDevice, bleConnection)
// open lock
openLock(bleDevice, bikeMode, bleConnection)
// getting user position
apiHelper.sendLockRequest(bleDevice.name, getPosition())
bleDevice.disconnect()
// this should be called on main thread once all the previous operations are finished
listener.onSuccess()
} catch (e: Exception) {
listener.onError(e)
}
}
job.join()
}

我当前的 Activity 代码 fragment :

bikeAccessClient.startRent(bikeBLEName, BikeMode.HYBRID, object :
StartRentListener {
override fun onSuccess() {
runOnUiThread {
// UI update here
}
}

最佳答案

您可以使用 withContext(Dispatchers.Main) {..} 函数与其他 Coroutine Dispatcher 一起执行您的部分代码。

kotlinx.coroutines.android 包含 Dispatchers.Main 函数的定义,它与 Android UI 正确集成。

在您的代码中使用显式 Dispatcher 非常容易出错。相反,我建议设计代码时明确要求较少。

我会写这样的东西:

fun uiActionHandlerToStartTheProcess() {
launch(Dispatchers.Main) {
val result = startRent(...) // no callback here, suspend function

//UI Update Here
}
}
suspend fun CoroutineScope.startRent() : SomeResultOfWork {
//that function offloads the execution to a IO (aka brackground) thread
return withContext(Dispatchers.IO){
//here goes your code from `startRent`
//use `suspendCancellableCoroutine {cont -> .. }` if you need to handle callbacks from it

SomeResultOfWork()
}

launch(Dispatchers.Main){..} block 中的代码在 UI 线程中执行。调用 startRent suspend 函数会暂停 UI 线程中的执行。一旦 startRent 准备好回复(来自后台线程),它就会恢复执行(由 Dispatchers.Main 完成,相当于 runOnUiThread { ...) 并从正确的线程执行 UI 更新

关于android - 在协程中切换到 UI 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com