|
7 | 7 |
|
8 | 8 | package io.element.android.libraries.matrix.impl.spaces
|
9 | 9 |
|
| 10 | +import io.element.android.libraries.core.coroutine.mapState |
10 | 11 | import io.element.android.libraries.matrix.api.core.RoomId
|
11 | 12 | import io.element.android.libraries.matrix.api.spaces.SpaceRoom
|
12 | 13 | import kotlinx.coroutines.flow.Flow
|
13 | 14 | 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 |
18 | 16 |
|
19 | 17 | /**
|
20 | 18 | * An in memory cache of space rooms.
|
21 | 19 | * Only caches Rooms with roomType [io.element.android.libraries.matrix.api.room.RoomType.Space].
|
22 | 20 | */
|
23 | 21 | 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()) |
27 | 23 | 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] } |
37 | 25 | }
|
38 | 26 |
|
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 | + } |
41 | 34 | }
|
42 | 35 | }
|
0 commit comments