Apply Transforamtion.map upon a LiveData<PagedList of objects>

613 views Asked by At

Inside my ViewModel class i have defined my paged list configuration

private val pagedListConfig: PagedList.Config = PagedList.Config.Builder().apply {
        setEnablePlaceholders(true)
        setInitialLoadSizeHint(10)
        setPageSize(10)
    }.build()

After that i retrieve from my Room database the messages that i want to show in my chatRoom Activity given to the groupId which i also take it from database and i make a switchMap Transformation

private var groupChatItem = MutableLiveData<GroupChatItem>()
    var chatRoomGroupMessages: LiveData<PagedList<MessageWithMsgQueueAccount>> =
        Transformations.switchMap(groupChatItem) {
            it?.let {
                LivePagedListBuilder(
                    messagesRepository.retrieveChatRoomGroupMessages(
                        chatRoomServerId,
                        it.groupId
                    ), pagedListConfig
                ).build()
            }
        }

All good up to now. Here i want to transform the List to expose a list of List, so basically i want to convert every element to a element through a function. So what i need is a Transformation.map() to the first LiveData so i can change it to another LiveData. But the problem is that i want to do it with Paged List. How can i do this?

var messageChatItems: LiveData<List<MessageChatItem>> = Transformations.map(chatRoomGroupMessages, messageChatItem -> {
   // Here is where i need to call the function
})


    fun convertGroupItemToMessageItem(): MessageChatItem {
       // here i make the convertion
    }
1

There are 1 answers

0
james04 On

So i get this to work as below

var chatRoomGroupMessages: LiveData<PagedList<MessageItem>> = Transformations.switchMap(groupChatItem) {
        it?.let {
                                   // Here is the messages from database
            val groupItemFactory = messagesRepository.getChatRoomMessages()
                .map { messageItem: ChatMessageItem? -> 
                      // Here i transform them
                      toMessageChatItem(messageItem, it.accountId) }
            
            LivePagedListBuilder(
                groupItemFactory, pagedListConfig
            ).build()
        }
    }

And the transform function is the "toMessageItem()" function