我正在構建一個使用 AWS 移動客戶端 SDK 的應用程式,但我想使用協程,但我遇到了一個問題,因為來自 AWS 的 SDK 正在使用回呼。
override suspend fun login(username: String, password: String): ResultResponse<SignInResult> {
AWSMobileClient.getInstance()
.signIn(username, password, null, object : Callback<SignInResult> {
override fun onResult(signInResult: SignInResult) {
ResultResponse.Success(signInResult)
}
override fun onError(e: Exception?) {
if (e != null) {
ResultResponse.Error(e)
}
}
})
}
知道如何解決此問題或正確執行此操作嗎?
問候
uj5u.com熱心網友回復:
可以使用suspendCoroutine()或將異步回呼轉換為同步掛起函式suspendCancellableCoroutine()。通常,您會創建相應異步呼叫的掛起擴展函式版本,以便您可以在通常使用 SDK 呼叫的任何地方使用它(而不是suspendCoroutine在每個位置使用,因為它有點笨拙)。
suspendCancellableCoroutine當 API 呼叫提供一種提前取消它的方法時使用。如果是這種情況,您可以讓您的掛起函式支持協程取消,因此如果關聯的協程被取消,API 呼叫將自動取消。正是您想要的,因為在 Android 上,lifecycleScope并viewModelScope在其關聯的生命周期結束時自動取消它們的協程。
我不知道您使用的是哪個版本的 AWS 開發工具包,但您的掛起功能大致如下所示:
suspend fun AWSMobileClient.signIn(userName: String, password: String, someParam: Any?): SignInResult = suspendCoroutine { continuation ->
signIn(userName, password, someParam, object : Callback<SignInResult> {
override fun onResult(signInResult: SignInResult) {
continuation.resume(signInResult)
}
override fun onError(e: Exception) {
continuation.resumeWithException(e)
}
})
}
我不知道第三個引數的型別,所以我只是把Any?.
現在您現有的功能將變為:
override suspend fun login(username: String, password: String): ResultResponse<SignInResult> {
return try {
val signInResult = AWSMobileClient.getInstance().signIn(username, password, null)
ResultResponse.Success(signInResult)
} catch(e: Exception) {
ResultResponse.Error(e)
}
}
我不確定是否ResultResponse是你自己的班級。如果是,請注意 Kotlin 標準庫已經包含一個 Result 類,這將使該函式通過使用更簡單runCatching:
override suspend fun login(username: String, password: String): Result<SignInResult> {
return runCatching {
AWSMobileClient.getInstance().signIn(username, password, null)
}
}
uj5u.com熱心網友回復:
將基于回呼的 API 轉換為掛起函式的常用方法是使用suspendCoroutine或suspendCancellableCoroutine(如果回呼 API 是可取消的)。
在你的情況下,它看起來像這樣:
override suspend fun login(username: String, password: String): SignInResult {
return suspendCoroutine { cont ->
AWSMobileClient.getInstance()
.signIn(username, password, null, object : Callback<SignInResult> {
override fun onResult(signInResult: SignInResult) {
cont.resume(signInResult)
}
override fun onError(e: Exception?) {
if (e != null) {
cont.resumeWithException(e)
}
}
})
}
}
這將掛起當前協程,直到使用結果或錯誤呼叫回呼。請注意,login()如果onError呼叫該方法將引發例外(這通常是您在使用掛起函式時想要的)。
uj5u.com熱心網友回復:
我假設您正在使用此 SDK
https://docs.aws.amazon.com/sdk-for-android/
如果您想使用支持 Kotlin 功能(例如協程)的AWS 開發工具包,請使用適用于 Kotlin的新AWS 開發工具包。
為 Kotlin 設定 AWS 開發工具包
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373198.html
下一篇:通過片段獲取父活動
