gpt4 book ai didi

android - 如何将这个(AdsWizz)Kotlin回调函数包装在协程中?

转载 作者:行者123 更新时间:2023-12-02 13:32:36 27 4
gpt4 key购买 nike

我是协程新手,很难弄清楚如何在协程中正确包装现有的回调。

我的目标是能够执行以下操作:

lifecycleScope.launch {
withContext(Dispatchers.Main) {
val theResult = getPreRollAd() //1. call this suspending func and wait for result

doSomethingWithResult(theResult) //2. now that the result is returned from AdsWizz API (below), do something with it
}
}

这是我要“包装”的AdsWizz API调用:
val adReqInterface: AdRequestHandlerInterface =  object :
AdRequestHandlerInterface {

override fun onResponseError(error: AdswizzSDKError) {
Timber.e("onResponseError $error")
}

override fun onResponseReady(adResponse: AdResponse) {
Timber.d( "onResponseReadySingleAd")

//this contains the url to the ad, title, etc..
!!!*** I WANT TO RETURN THE adResponse.mediaFile?.source string back to "theResult" variable above (in lifecycleScope.launch {.... )


}
}

try {
AdswizzSDK.getAdsLoader().requestAd(adReqParams, adReqInterface)

} catch (e: IllegalArgumentException) {
Timber.d( "IllegalArgumentException")
} catch (e: SecurityException) {
Timber.d( "SecurityException")
} catch (e: Exception) {
Timber.d( "other exception")
e.printStackTrace()
}

我尝试使用 suspendCoroutine {...进行包装,但是没有任何效果。非常感谢有人帮助您以正确的方式实现这一目标。

最佳答案

正确的方法是使用suspendCancellableCoroutine。它可以返回结果或可以取消,但有异常(exception)。

suspend fun getPreRollAd(): AdResponse {
return suspendCancellableCoroutine {

...

val adReqInterface: AdRequestHandlerInterface = object : AdRequestHandlerInterface {

override fun onResponseError(error: AdswizzSDKError) {
Timber.e("onResponseError $error")
it.cancel(error)
}

override fun onResponseReady(adResponse: AdResponse) {
Timber.d( "onResponseReadySingleAd")
it.resume(adResponse)
}

}

AdswizzSDK.getAdsLoader().requestAd(adReqParams, adReqInterface)
}

}


viewModelScope.launch {
val result = try {
getPreRollAd()
} catch(e: Throwable) {
null
}

...
}

关于android - 如何将这个(AdsWizz)Kotlin回调函数包装在协程中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60460930/

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