https://kotlinlang.org logo
#coroutines
Title
# coroutines
o

Orhan Tozan

11/05/2020, 1:47 PM
I am trying to construct the following Flow, but with no luck. I am trying to do something like below, but it obviously doesn't compile (it's pseudo code). As you can see, I am trying to map a
chatConversationsFlow: Flow<List<ChatConversation>>
to a
lastMessagesFlow: Flow<List<String>>
. When the last message of a conversation is sent by me, the result will be of the format
"You: ${chatConversation.lastMessage}"
. But when the last message of a conversation is sent by someone else than me, I first need to get
userFlow: Flow<User>
of the specific user, then the result will be of the format
"${user.name}: ${chatConversation.lastMessage}"
. What would be the best (preferably most idiomatic) approach to achieve this in Flow/Coroutines?
Copy code
private fun lastMessagesFlow(
    chatConversationsFlow: Flow<List<ChatConversation>>
): Flow<List<String>> = flow {
    emit(listOf("Loading"))

    emitAll(
        chatConversationsFlow.map { chatConversations ->
            chatConversations.map { chatConversation ->
                if (chatConversation.lastMessageSentByUserId == -1) "You: ${chatConversation.lastMessage}"
                else {
                    val userFlow: Flow<User> = userFlow(userId = chatConversation.lastMessageSentByUserId)
                    userFlow.map { user ->
                        "${user.name}: ${chatConversation.lastMessage}"
                    }
                }

            }
        }
    )
}
It was challenging, but I managed to do it😁 (with use of combine() and flattenMerge())
6 Views