@@ -47,6 +47,7 @@ class AdapterTeamList(
4747 private var filteredList: List <RealmMyTeam > = emptyList()
4848 private lateinit var prefData: SharedPrefManager
4949 private val teamStatusCache = mutableMapOf<String , TeamStatus >()
50+ private val visitCountsCache = mutableMapOf<String , Long >()
5051 private var visitCounts: Map <String , Long > = emptyMap()
5152 private var updateListJob: Job ? = null
5253
@@ -261,8 +262,13 @@ class AdapterTeamList(
261262 }
262263
263264 val teamIds = validTeams.mapNotNull { it._id ?.takeIf { id -> id.isNotBlank() } }
264- val visitCountsDeferred = async(Dispatchers .IO ) {
265- teamRepository.getRecentVisitCounts(teamIds)
265+ val (cachedVisitIds, nonCachedVisitIds) = teamIds.partition { it in visitCountsCache }
266+ val visitCountsDeferred = if (nonCachedVisitIds.isNotEmpty()) {
267+ async(Dispatchers .IO ) {
268+ teamRepository.getRecentVisitCounts(nonCachedVisitIds)
269+ }
270+ } else {
271+ async { emptyMap<String , Long >() }
266272 }
267273
268274 val statusResults = mutableMapOf<String , TeamStatus >()
@@ -297,6 +303,8 @@ class AdapterTeamList(
297303 }
298304
299305 val newVisitCounts = visitCountsDeferred.await()
306+ newVisitCounts.forEach { (id, count) -> visitCountsCache[id] = count }
307+ val allVisitCounts = cachedVisitIds.associateWith { visitCountsCache[it]!! } + newVisitCounts
300308 val sortedTeams = validTeams.sortedWith(
301309 compareByDescending<RealmMyTeam > { team ->
302310 val teamId = team._id .orEmpty()
@@ -307,7 +315,7 @@ class AdapterTeamList(
307315 else -> 1
308316 }
309317 }.thenByDescending { team ->
310- newVisitCounts [team._id .orEmpty()] ? : 0L
318+ allVisitCounts [team._id .orEmpty()] ? : 0L
311319 }
312320 )
313321
@@ -321,7 +329,7 @@ class AdapterTeamList(
321329 createdDate = team.createdDate,
322330 type = team.type,
323331 status = team.status,
324- visitCount = newVisitCounts [teamId] ? : 0L ,
332+ visitCount = allVisitCounts [teamId] ? : 0L ,
325333 teamStatus = teamStatusCache[cacheKey]
326334 )
327335 }
@@ -330,7 +338,7 @@ class AdapterTeamList(
330338 DiffUtil .calculateDiff(TeamDiffCallback (oldList, newList))
331339 }
332340
333- visitCounts = newVisitCounts
341+ visitCounts = allVisitCounts
334342 filteredList = sortedTeams
335343 diffResult.dispatchUpdatesTo(this @AdapterTeamList)
336344 updateCompleteListener?.onUpdateComplete(filteredList.size)
@@ -409,6 +417,12 @@ class AdapterTeamList(
409417 this .type = type
410418 }
411419
420+ fun cleanup () {
421+ scope.cancel()
422+ teamStatusCache.clear()
423+ visitCountsCache.clear()
424+ }
425+
412426 override fun getItemCount (): Int = filteredList.size
413427
414428 class ViewHolderTeam (val binding : ItemTeamListBinding ) : RecyclerView.ViewHolder(binding.root)
0 commit comments