Skip to content

Commit acfccfa

Browse files
committed
refactor: Use threadsafe data structures to avoid any race conditions
1 parent b3f1d5b commit acfccfa

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

android/src/main/kotlin/com/mparticle/mparticle_flutter_sdk/RoktEventHandler.kt

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.mparticle.mparticle_flutter_sdk
22

33
import android.app.Activity
4+
import android.os.Build
5+
import androidx.annotation.RequiresApi
46
import androidx.lifecycle.Lifecycle
57
import androidx.lifecycle.LifecycleOwner
68
import androidx.lifecycle.lifecycleScope
@@ -11,11 +13,13 @@ import io.flutter.plugin.common.EventChannel
1113
import kotlinx.coroutines.Job
1214
import kotlinx.coroutines.flow.Flow
1315
import kotlinx.coroutines.launch
14-
import java.util.ArrayDeque
16+
import java.util.concurrent.ConcurrentHashMap
17+
import java.util.concurrent.ConcurrentLinkedDeque
1518

19+
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
1620
class RoktEventHandler(private val messenger: BinaryMessenger) {
1721

18-
private val eventListeners = mutableMapOf<Any?, ArrayDeque<EventChannel.EventSink>>()
22+
private val eventListeners = ConcurrentHashMap<Any?, ConcurrentLinkedDeque<EventChannel.EventSink>>()
1923
private val eventSubscriptions = mutableMapOf<String, Job?>()
2024

2125
init {
@@ -75,18 +79,18 @@ class RoktEventHandler(private val messenger: BinaryMessenger) {
7579
sink: EventChannel.EventSink?,
7680
) {
7781
sink?.let {
78-
val sinks = eventListeners.getOrPut(arguments) { ArrayDeque() }
82+
val sinks = eventListeners.getOrPut(arguments ?: "") { ConcurrentLinkedDeque() }
7983
sinks.addLast(it)
8084
}
8185
}
8286

8387
override fun onCancel(arguments: Any?) {
84-
val sinks = eventListeners[arguments]
88+
val sinks = eventListeners[arguments ?: ""]
8589
if (sinks?.isNotEmpty() == true) {
8690
sinks.removeLast()
8791
}
8892
if (sinks?.isEmpty() == true) {
89-
eventListeners.remove(arguments)
93+
eventListeners.remove(arguments ?: "")
9094
}
9195
}
9296
},

0 commit comments

Comments
 (0)