@@ -8,7 +8,6 @@ import kotlinx.coroutines.withContext
8
8
import org.wordpress.android.fluxc.store.WCProductStore
9
9
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload
10
10
import java.lang.ref.WeakReference
11
- import java.util.concurrent.CopyOnWriteArrayList
12
11
import javax.inject.Inject
13
12
import javax.inject.Singleton
14
13
@@ -28,7 +27,7 @@ class ProductImageMap @Inject constructor(
28
27
fun onProductFetched (remoteProductId : Long )
29
28
}
30
29
31
- private val observers: MutableList <WeakReference <OnProductFetchedListener >> = CopyOnWriteArrayList ()
30
+ private val observers: MutableList <WeakReference <OnProductFetchedListener >> = mutableListOf ()
32
31
33
32
private val map by lazy {
34
33
HashMap <Long , String >()
@@ -64,12 +63,14 @@ class ProductImageMap @Inject constructor(
64
63
val result = productStore.fetchSingleProduct(FetchSingleProductPayload (site, remoteProductId))
65
64
if (! result.isError) {
66
65
withContext(dispatchers.main) {
66
+ // Collect references to remove
67
+ val toRemove = mutableListOf<WeakReference <OnProductFetchedListener >>()
67
68
observers.forEach { weakReference ->
68
- // notify the observer
69
- weakReference.get()?.onProductFetched(remoteProductId)
70
- // remove the weak reference if the observer was garbage collected
71
- ? : observers.remove(weakReference)
69
+ // notify the observer or collect it for removal if it's been garbage collected
70
+ weakReference.get()?.onProductFetched(remoteProductId) ? : toRemove.add(weakReference)
72
71
}
72
+ // Remove the collected references
73
+ observers.removeAll(toRemove)
73
74
}
74
75
}
75
76
}
0 commit comments