Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary map instance creations on Presences #200

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions yorkie/src/main/kotlin/dev/yorkie/core/Presences.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,34 @@ import dev.yorkie.document.time.ActorID
public typealias P = Map<String, String>

public class Presences private constructor(
private val map: MutableMap<ActorID, MutableMap<String, String>>,
private val map: Map<ActorID, Map<String, String>>,
) : Map<ActorID, P> by map {

internal constructor() : this(mutableMapOf())

public operator fun plus(presenceInfo: Pair<ActorID, P>): Presences {
val (actorID, presence) = presenceInfo
val newPresence = map[actorID].orEmpty() + presence
return (map + (actorID to newPresence)).asPresences()
return Presences(map + (actorID to newPresence))
}

public operator fun minus(actorID: ActorID): Presences = (map - actorID).asPresences()
public operator fun minus(actorID: ActorID): Presences {
return Presences(map - actorID)
}

override fun toString(): String {
return map.entries.toString()
}

companion object {
public fun Map<ActorID, P>.asPresences(): Presences {
return Presences(mapValues { it.value.toMutableMap() }.toMutableMap())
return if (this is Presences) {
Presences(map)
} else {
Presences(this)
}
}

public fun Pair<ActorID, P>.asPresences(): Presences {
return Presences(mutableMapOf(first to second.toMutableMap()))
return Presences(mapOf(this))
}

internal val UninitializedPresences = Presences(
Expand Down
2 changes: 1 addition & 1 deletion yorkie/src/main/kotlin/dev/yorkie/document/Document.kt
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public class Document(
public val presences: StateFlow<Presences> =
combine(_presences, onlineClients) { presences, onlineClients ->
presences.filterKeys { it in onlineClients + changeID.actor }.asPresences()
}.stateIn(scope, SharingStarted.Eagerly, _presences.value.asPresences()).also {
}.stateIn(scope, SharingStarted.Eagerly, _presences.value).also {
scope.launch {
it.collect { presences ->
presenceEventQueue.addAll(pendingPresenceEvents)
Expand Down
Loading