【发布时间】:2021-04-07 16:10:31
【问题描述】:
我想使用 kotlin 协程从回调函数 async/await 样式的 javascript 中获得响应。
这是我的回调函数
offlineCatalog.findOfflineVideoById(id, object : OfflineCallback<Video> {
override fun onSuccess(video: Video?) {
video?.let {
//Return This Video
} ?: kotlin.run {
findVideoOnline(id, state)
}
}
override fun onFailure(throwable: Throwable?) {
findVideoOnline(id, state)
}
})
onlineCatalog.findVideoByID(id, object : VideoListener() {
override fun onVideo(video: Video?) {
video?.let {
//Return This Video
} ?: kotlin.run {
Log.e("Return Error")
}
}
override fun onError(errors: MutableList<CatalogError>) {
super.onError(errors)
Log.e("Return Error")
}
})
如果OfflineCatalog 出错,我想调用将从OfflineCatalog 返回视频对象的函数,然后从OnlineCatalog 搜索。
比如
try{
val video:Video? = getVideo(id:String)
//do something
}catch(throwable:Throwable){
Log.e("Video not found")
}
更新:我的实施n
这是我想出来的
suspend fun getVideo(id: String): Video? = withContext(Dispatchers.IO) {
var video = getVideoOffline(id)
video?.let { video } ?: kotlin.run { getVideoOnline(id) }
}
suspend fun getVideoOffline(id: String): Video? = suspendCancellableCoroutine { cont ->
(offlineCatalog.findOfflineVideoById(id, object : OfflineCallback<Video> {
override fun onSuccess(video: Video?) = cont.resume(video)
override fun onFailure(throwable: Throwable?) = cont.resume(null)
}))
}
suspend fun getVideoOnline(id: String): Video? = suspendCancellableCoroutine { cont ->
catalog.findVideoByID(id, object : VideoListener() {
override fun onVideo(video: Video?) = cont.resume(video)
override fun onError(errors: MutableList<CatalogError>) = cont.resume(null)
})
}
用法-
CoroutineScope(Dispatchers.Main).launch {
getVideo(id)?.let {
//Do Something
} ?: kotlin.run{
//Video Not Found
}
}
【问题讨论】:
-
你应该让
findOfflineVideoById和findVideoByID挂起函数 -
但我不能在回调中调用 findVideoByid 因为我们必须在那里调用 resume
-
显示这些函数
-
这些是来自 Brightcove 播放器的预建函数。 Catalog & OfflineCatalog
-
好的,那么
getVideo函数会有点复杂..