gpt4 book ai didi

kotlin - 如何从非暂停回调函数从LiveData构建器发出

转载 作者:行者123 更新时间:2023-12-02 13:34:50 25 4
gpt4 key购买 nike

我是LiveData和Kotlin Coroutines的新手。我正在尝试使用Chromium Cronet库从我的存储库类发出请求以返回LiveData对象。为了返回liveData,我使用了新的LiveData构建器(coroutines with LiveData)。成功的Cronet请求将如何发出结果?

class CustomRepository @Inject constructor(private val context: Context, private val gson: Gson) : Repository {
private val coroutineDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()

override suspend fun getLiveData(): LiveData<List<MyItem>> = liveData(coroutineDispatcher) {
val executor = Executors.newSingleThreadExecutor()
val cronetEngineBuilder = CronetEngine.Builder(context)
val cronetEngine = cronetEngineBuilder.build()
val requestBuilder = cronetEngine.newUrlRequestBuilder(
"http://www.exampleApi.com/example",
CustomRequestCallback(gson),
executor
)
val request: UrlRequest = requestBuilder.build()
request.start()
}

class CustomRequestCallback(private val gson: Gson) : UrlRequest.Callback() {

override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) {
byteBuffer?.flip()
byteBuffer?.let {
val byteArray = ByteArray(it.remaining())
it.get(byteArray)
String(byteArray, Charset.forName("UTF-8"))
}.apply {
val myItems = gson.fromJson(this, MyItem::class.java)
// THIS IS WHAT I WANT TO EMIT
// emit(myItems) doesn't work since I'm not in a suspending function
}
byteBuffer?.clear()
request?.read(byteBuffer)
}

// other callbacks not shown
}

}

最佳答案

该解决方案涉及将UrlRequest.Callback传统回调结构包装在suspendCoroutine构建器中。

我还通过讨论Medium articleCronet integration with LiveData and Kotlin Coroutines捕获了我的学习。

override suspend fun getLiveData(): LiveData<List<MyItem>> = liveData(coroutineDispatcher) {

lateinit var result: List<MyItem>
suspendCoroutine<List<MyItem>> { continuation ->

val requestBuilder = cronetEngine.newUrlRequestBuilder(
"http://www.exampleApi.com/example",
object : UrlRequest.Callback() {

// other callbacks not shown

override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) {
byteBuffer?.flip()
byteBuffer?.let {
val byteArray = ByteArray(it.remaining())
it.get(byteArray)
String(byteArray, Charset.forName("UTF-8"))
}.apply {
val myItems = gson.fromJson(this, MyItem::class.java)
result = myItems
continuation.resume(result)
}
byteBuffer?.clear()
request?.read(byteBuffer)
},
executor
)
val request: UrlRequest = requestBuilder.build()
request.start()

}
emit(result)
}

关于kotlin - 如何从非暂停回调函数从LiveData构建器发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895770/

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