diff --git a/app/src/main/java/com/futo/platformplayer/sync/internal/SyncSession.kt b/app/src/main/java/com/futo/platformplayer/sync/internal/SyncSession.kt index f7754710..575b8af8 100644 --- a/app/src/main/java/com/futo/platformplayer/sync/internal/SyncSession.kt +++ b/app/src/main/java/com/futo/platformplayer/sync/internal/SyncSession.kt @@ -17,6 +17,8 @@ interface IAuthorizable { class SyncSession : IAuthorizable { private val _channels: MutableList = mutableListOf() + @Volatile + private var _snapshot: Array = emptyArray() private var _authorized: Boolean = false private var _remoteAuthorized: Boolean = false private val _onAuthorized: (session: SyncSession, isNewlyAuthorized: Boolean, isNewSession: Boolean) -> Unit @@ -83,6 +85,8 @@ class SyncSession : IAuthorizable { synchronized(_channels) { _channels.add(channel) + _channels.sortBy { it.linkType.ordinal } + _snapshot = _channels.toTypedArray() connected = _channels.isNotEmpty() } @@ -124,15 +128,20 @@ class SyncSession : IAuthorizable { fun removeChannel(channel: IChannel) { synchronized(_channels) { _channels.remove(channel) + _snapshot = _channels.toTypedArray() connected = _channels.isNotEmpty() } } fun close() { - synchronized(_channels) { - _channels.toTypedArray() - }.forEach { it.close() } - + val toClose = synchronized(_channels) { + val arr = _channels.toTypedArray() + _channels.clear() + _snapshot = emptyArray() + connected = false + arr + } + toClose.forEach { it.close() } _onClose(this) } @@ -209,13 +218,12 @@ class SyncSession : IAuthorizable { fun send(opcode: UByte, subOpcode: UByte, data: ByteBuffer? = null, contentEncoding: ContentEncoding? = null) { ensureNotMainThread() - val channels = synchronized(_channels) { _channels.sortedBy { it.linkType.ordinal }.toList() } + val channels = _snapshot if (channels.isEmpty()) { - //TODO: Should this throw? - Logger.v(TAG, "Packet was not sent (opcode = $opcode, subOpcode = $subOpcode) due to no connected sockets") + Logger.v(TAG, "Packet was not sent … no connected sockets") return } - + var sent = false for (channel in channels) { try {