Kotlin list transformations

I’m building a chat platform, where I’m reading my list of messages from Local Room DB (ChatModel). I need to add date separators between these messages. I’ve to use multiple view holders and thus created a sealed class for differentiating items

sealed class ChatUiModel { data class ChatItem(val message: ChatModel) : ChatUiModel() data class DateSeparatorItem(val time: String) : ChatUiModel() } 

I require to convert the list with date separate items in between 2 models of the list, I’m not proficient with Collection functions in kotlin and confused between map/flatmap etc.

val items = mutableListOf<ChatUiModel>() val data = messages.listIterator() for (item in data) { if (data.hasPrevious()) if (data.previous().time < item.time) items.add(ChatUiModel.DateSeparatorItem(item.time)) items.add(ChatUiModel.ChatItem(item)) } Timber.i("CHAT = $items") 

submitted by /u/DarkAbhi
[link] [comments]