How to implement Promise.all like functionality in kotlin

Rahul Saini

Am trying to get messages from twillio server using its sdk method so on calling the method it return callback to return the List of messages. I have list of conversation,i want to get all messages for conversation so am using forEach like this

  allConversations.forEach { conversation ->
            conversation.getMessageByIndex(conversation.lastMessageIndex){
                conversationLastMessages[conversation.sid] = it
            }
        }

So i want to wait until all listners get executed and then want to change the state of ui.

Sergey

You can make all requests in parallel and wait for all of them to finish following next steps:

  1. Create a suspend function getMessage, which will be responsible for suspending the calling coroutine until request is executed. You can use suspendCoroutine or suspendCancellableCoroutine for that:

    suspend fun getMessage(conversation: Conversation) = suspendCoroutine<Message?> { continuation ->
        conversation.getMessageByIndex(conversation.lastMessageIndex, object : CallbackListener<Message> {
            override fun onError(errorInfo: ErrorInfo) {
                continuation.resume(null) // resume calling coroutine
                // or continuation.resumeWithException() depend whether you want to handle Exception or not
            }
    
            override fun onSuccess(result: Message) {
                continuation.resume(result) // resume calling coroutine
            }
        })
    }
    
  2. Run requests in parallel using async coroutine builder and Dispatchers.IO dispatcher to offload work from the Main Thread:

    async(Dispatchers.IO) {
        getMessage(conversation)
    }
    
  3. To run all this you need to use some instance of CoroutineScope to launch a coroutine. In ViewModel it can be viewModelScope, in Activity/Fragment - lifecycleScope. For example in ViewModel:

    viewModelScope.launch {
        val allConversations = ...
    
        allConversations.map { conversation ->
            async(Dispatchers.IO) {
                getMessage(conversation)
            }
        }.awaitAll() // waiting for all request to finish executing in parallel
         .forEach { message ->   // iterate over List<Message> and fill conversationLastMessages
             conversationLastMessages[message.getConversationSid()] = message
         }
    
         // here all requests are completed and UI can be updated
    }
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Coroutines And Firebase: How to Implement Javascript-like Promise.all()

Angular: How to implement ng-include like functionality in Angular 5?

How to implement functionality like Facebook "New Story" feature?

Implement Sliding Drawer like functionality

Implement Tag functionality like Instagram?

How to implement check all functionality for Ant Design check box

How to implement signin functionality?

How to implement Search Functionality

Implement 'Entrypoint' like functionality in Cloud Native Buildpack

how do i implement java like constructors in kotlin

How to implement the equivalent of Promise.all for my Task implementation?

How can a Leiningen plugin implement profile-like functionality for a plugin-specific project section?

How to implement search functionality on table?

How to Implement tab functionality in React

How to implement CRTP functionality in python?

how to implement printing functionality in android

Implement functionality for all the UIViewControllers using Swift

Promise how to implement in this situation?

React how should be the like functionality

Better way to implement 'like tweet' functionality with react native and redux

How to implement finalize() in kotlin?

how to implement an applyif for Kotlin?

How to implement RecyclerViewPager in kotlin?

How to implement "decorator" functionality in a "class" object?

How to implement ctype.h functionality in JavaScript?

How to implement Filter/Search functionality in ListAdapter - WORKING

How can I implement "recycle bin" functionality?

How to implement Save As Draft functionality in liferay 7

How To Implement Import data Functionality With Golang?