Skip to content

Commit 697652a

Browse files
committed
Iterate on SpaceRoomCache thanks to SpaceRoomCacheTest
1 parent 959cb4f commit 697652a

File tree

1 file changed

+11
-18
lines changed
  • libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/spaces

1 file changed

+11
-18
lines changed

libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/spaces/SpaceRoomCache.kt

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,29 @@
77

88
package io.element.android.libraries.matrix.impl.spaces
99

10+
import io.element.android.libraries.core.coroutine.mapState
1011
import io.element.android.libraries.matrix.api.core.RoomId
1112
import io.element.android.libraries.matrix.api.spaces.SpaceRoom
1213
import kotlinx.coroutines.flow.Flow
1314
import kotlinx.coroutines.flow.MutableStateFlow
14-
import kotlinx.coroutines.flow.asStateFlow
15-
import kotlinx.coroutines.sync.Mutex
16-
import kotlinx.coroutines.sync.withLock
17-
import java.util.concurrent.ConcurrentHashMap
15+
import kotlinx.coroutines.flow.update
1816

1917
/**
2018
* An in memory cache of space rooms.
2119
* Only caches Rooms with roomType [io.element.android.libraries.matrix.api.room.RoomType.Space].
2220
*/
2321
class SpaceRoomCache {
24-
private val inMemoryCache = ConcurrentHashMap<RoomId, MutableStateFlow<SpaceRoom?>>()
25-
private val mutex = Mutex()
26-
22+
private val inMemoryCache = MutableStateFlow<Map<RoomId, SpaceRoom?>>(emptyMap())
2723
fun getSpaceRoomFlow(roomId: RoomId): Flow<SpaceRoom?> {
28-
return getMutableFlow(roomId).asStateFlow()
29-
}
30-
31-
suspend fun update(spaceRooms: List<SpaceRoom>) = mutex.withLock {
32-
spaceRooms
33-
.filter { it.isSpace }
34-
.forEach { spaceRoom ->
35-
getMutableFlow(spaceRoom.roomId).value = spaceRoom
36-
}
24+
return inMemoryCache.mapState { it[roomId] }
3725
}
3826

39-
private fun getMutableFlow(roomId: RoomId): MutableStateFlow<SpaceRoom?> {
40-
return inMemoryCache.getOrPut(roomId, { MutableStateFlow(null) })
27+
fun update(spaceRooms: List<SpaceRoom>) {
28+
inMemoryCache.update { currentValues ->
29+
val newValues = spaceRooms
30+
.filter { it.isSpace }
31+
.associateBy { it.roomId }
32+
currentValues + newValues
33+
}
4134
}
4235
}

0 commit comments

Comments
 (0)