Iterate on SpaceRoomCache thanks to SpaceRoomCacheTest
This commit is contained in:
parent
54daa6251c
commit
00d07f970a
1 changed files with 11 additions and 18 deletions
|
|
@ -7,36 +7,29 @@
|
||||||
|
|
||||||
package io.element.android.libraries.matrix.impl.spaces
|
package io.element.android.libraries.matrix.impl.spaces
|
||||||
|
|
||||||
|
import io.element.android.libraries.core.coroutine.mapState
|
||||||
import io.element.android.libraries.matrix.api.core.RoomId
|
import io.element.android.libraries.matrix.api.core.RoomId
|
||||||
import io.element.android.libraries.matrix.api.spaces.SpaceRoom
|
import io.element.android.libraries.matrix.api.spaces.SpaceRoom
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An in memory cache of space rooms.
|
* An in memory cache of space rooms.
|
||||||
* Only caches Rooms with roomType [io.element.android.libraries.matrix.api.room.RoomType.Space].
|
* Only caches Rooms with roomType [io.element.android.libraries.matrix.api.room.RoomType.Space].
|
||||||
*/
|
*/
|
||||||
class SpaceRoomCache {
|
class SpaceRoomCache {
|
||||||
private val inMemoryCache = ConcurrentHashMap<RoomId, MutableStateFlow<SpaceRoom?>>()
|
private val inMemoryCache = MutableStateFlow<Map<RoomId, SpaceRoom?>>(emptyMap())
|
||||||
private val mutex = Mutex()
|
|
||||||
|
|
||||||
fun getSpaceRoomFlow(roomId: RoomId): Flow<SpaceRoom?> {
|
fun getSpaceRoomFlow(roomId: RoomId): Flow<SpaceRoom?> {
|
||||||
return getMutableFlow(roomId).asStateFlow()
|
return inMemoryCache.mapState { it[roomId] }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun update(spaceRooms: List<SpaceRoom>) = mutex.withLock {
|
fun update(spaceRooms: List<SpaceRoom>) {
|
||||||
spaceRooms
|
inMemoryCache.update { currentValues ->
|
||||||
.filter { it.isSpace }
|
val newValues = spaceRooms
|
||||||
.forEach { spaceRoom ->
|
.filter { it.isSpace }
|
||||||
getMutableFlow(spaceRoom.roomId).value = spaceRoom
|
.associateBy { it.roomId }
|
||||||
}
|
currentValues + newValues
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getMutableFlow(roomId: RoomId): MutableStateFlow<SpaceRoom?> {
|
|
||||||
return inMemoryCache.getOrPut(roomId, { MutableStateFlow(null) })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue