简体   繁体   中英

Android: Kotlin getting data from callback and emit with flow

Everyone, I have this method and want to emit listmessage but list is unable to get the list of values, How can I do it?

fun ReadMessage(dialog: QBChatDialog) = flow{
        try {
                
                    var list: ArrayList<QBChatMessage> = ArrayList()
            chatHelper.ReadChatHistory(dialog, object : QBEntityCallback<ArrayList<QBChatMessage>>{
                override fun onSuccess(listmessage: ArrayList<QBChatMessage>?, p1: Bundle?) {
                    Log.e(TAG, "Reading Message: $p0")
                }
                override fun onError(p0: QBResponseException?) {
                    Log.e(TAG, "Reading Message Exception: $p0")
                }
            })
            Log.e(TAG, "Reading Messageeeeeeeeee: $list")
            emit(list)
        }catch (e: Exception){
            Log.e(TAG, "Reading Message Exceptionn: $e")
        }
    }

You should use CompletableDeferred . You can do something like this:

    fun readMessage(dialog: QBChatDialog): Flow<ArrayList<QBChatMessage>> {
        val historyDeferred = CompletableDeferred<ArrayList<QBChatMessage>>()
        chatHelper.ReadChatHistory(dialog, object : QBEntityCallback<ArrayList<QBChatMessage>> {
            override fun onSuccess(listmessage: ArrayList<QBChatMessage>?, p1: Bundle?) {
                historyDeferred.complete(listmessage ?: arrayListOf())
            }

            override fun onError(p0: QBResponseException?) {
                historyDeferred.completeExceptionally(p0 ?: CancellationException())
            }
        })
        return flow {
            try {
                emit(historyDeferred.await())
            } catch (e: Exception) {
                Log.e(TAG, "Reading Message Exceptionn: $e")
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM