11package org.phoenixframework
22
33import java.lang.IllegalStateException
4+ import java.util.concurrent.ConcurrentHashMap
5+ import java.util.concurrent.ConcurrentLinkedQueue
46
57
68class PhxChannel (
@@ -44,7 +46,7 @@ class PhxChannel(
4446
4547
4648 var state: PhxChannel .PhxState
47- var bindings: MutableList < Triple < String , Int , (PhxMessage ) - > Unit >>
49+ val bindings: ConcurrentHashMap < String , ConcurrentLinkedQueue < Pair < Int , (PhxMessage ) - > Unit > >>
4850 var bindingRef: Int
4951 var timeout: Long
5052 var joinedOnce: Boolean
@@ -58,7 +60,7 @@ class PhxChannel(
5860
5961 init {
6062 this .state = PhxChannel .PhxState .CLOSED
61- this .bindings = ArrayList ()
63+ this .bindings = ConcurrentHashMap ()
6264 this .bindingRef = 0
6365 this .timeout = socket.timeout
6466 this .joinedOnce = false
@@ -197,7 +199,9 @@ class PhxChannel(
197199 val ref = bindingRef
198200 this .bindingRef = ref + 1
199201
200- this .bindings.add(Triple (event, ref, callback))
202+ this .bindings.getOrPut(event) { ConcurrentLinkedQueue () }
203+ .add(ref to callback)
204+
201205 return ref
202206 }
203207
@@ -219,9 +223,11 @@ class PhxChannel(
219223 public fun off (event : String , ref : Int? = null) {
220224 // Remove any subscriptions that match the given event and ref ID. If no ref
221225 // ID is given, then remove all subscriptions for an event.
222- this .bindings = bindings
223- .filterNot { it.first == event && (ref == null || ref == it.second) }
224- .toMutableList()
226+ if (ref != null ) {
227+ this .bindings[event]?.removeIf{ ref == it.first }
228+ } else {
229+ this .bindings.remove(event)
230+ }
225231 }
226232
227233 /* *
@@ -333,9 +339,7 @@ class PhxChannel(
333339 */
334340 fun trigger (message : PhxMessage ) {
335341 val handledMessage = onMessage(message)
336- this .bindings
337- .filter { it.first == message.event }
338- .forEach { it.third(handledMessage) }
342+ this .bindings[message.event]?.forEach { it.second(handledMessage) }
339343 }
340344
341345 /* *
0 commit comments