@@ -3,6 +3,9 @@ package com.getcode.network
33import android.annotation.SuppressLint
44import androidx.paging.Pager
55import androidx.paging.PagingConfig
6+ import androidx.paging.PagingData
7+ import androidx.paging.PagingSource
8+ import androidx.paging.cachedIn
69import com.getcode.ed25519.Ed25519.KeyPair
710import com.getcode.manager.SessionManager
811import com.getcode.model.Chat
@@ -20,6 +23,8 @@ import com.getcode.network.source.ChatMessagePagingSource
2023import com.getcode.utils.ErrorUtils
2124import kotlinx.coroutines.CoroutineScope
2225import kotlinx.coroutines.Dispatchers
26+ import kotlinx.coroutines.GlobalScope
27+ import kotlinx.coroutines.flow.Flow
2328import kotlinx.coroutines.flow.MutableStateFlow
2429import kotlinx.coroutines.flow.StateFlow
2530import kotlinx.coroutines.flow.asStateFlow
@@ -53,9 +58,21 @@ class HistoryController @Inject constructor(
5358 val chats: StateFlow <List <Chat >? >
5459 get() = _chats .asStateFlow()
5560
56- fun chatMessagePager (chatId : ID ) = Pager (
61+
62+ private val pagerMap = mutableMapOf<ID , PagingSource <Cursor , ChatMessage >>()
63+ private val chatFlows = mutableMapOf<ID , Flow <PagingData <ChatMessage >>>()
64+
65+ private fun chatMessagePager (chatId : ID ) = Pager (
5766 PagingConfig (pageSize = 20 )
58- ) { ChatMessagePagingSource (client, owner()!! , chatId) }
67+ ) {
68+ pagerMap[chatId] ? : ChatMessagePagingSource (client, owner()!! , chatId).also {
69+ pagerMap[chatId] = it
70+ }
71+ }
72+
73+ fun chatFlow (chatId : ID ) = chatFlows[chatId] ? : chatMessagePager(chatId).flow.cachedIn(GlobalScope ).also {
74+ chatFlows[chatId] = it
75+ }
5976
6077 val unreadCount = chats
6178 .filterNotNull()
@@ -143,7 +160,7 @@ class HistoryController @Inject constructor(
143160
144161 private suspend fun fetchLatestMessageForChat (id : List <Byte >): Result <ChatMessage ?> {
145162 val encodedId = id.toByteArray().encodeBase64()
146- Timber .d(" fetching messages for $encodedId " )
163+ Timber .d(" fetching last message for $encodedId " )
147164 val owner = owner() ? : return Result .success(null )
148165 return client.fetchMessagesFor(owner, id, limit = 1 )
149166 .onFailure {
0 commit comments