如何从非挂起的回调函数中从LiveData构建器中发出

问题描述 投票:1回答:1

我是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
}

}

kotlin android-livedata coroutine kotlin-coroutines cronet
1个回答
0
投票

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

[我还在Medium article中记录了我的学习,该课程讨论了Cronet 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)
}
© www.soinside.com 2019 - 2024. All rights reserved.