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

Fix ProductImageMap ConcurrentModificationException by Safely Managing WeakReferences #10910

Merged
merged 2 commits into from
Feb 26, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import kotlinx.coroutines.withContext
import org.wordpress.android.fluxc.store.WCProductStore
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton

Expand All @@ -28,7 +27,7 @@ class ProductImageMap @Inject constructor(
fun onProductFetched(remoteProductId: Long)
}

private val observers: MutableList<WeakReference<OnProductFetchedListener>> = CopyOnWriteArrayList()
private val observers: MutableList<WeakReference<OnProductFetchedListener>> = mutableListOf()

private val map by lazy {
HashMap<Long, String>()
Expand Down Expand Up @@ -64,12 +63,14 @@ class ProductImageMap @Inject constructor(
val result = productStore.fetchSingleProduct(FetchSingleProductPayload(site, remoteProductId))
if (!result.isError) {
withContext(dispatchers.main) {
// Collect references to remove
val toRemove = mutableListOf<WeakReference<OnProductFetchedListener>>()
observers.forEach { weakReference ->
// notify the observer
weakReference.get()?.onProductFetched(remoteProductId)
// remove the weak reference if the observer was garbage collected
?: observers.remove(weakReference)
// notify the observer or collect it for removal if it's been garbage collected
weakReference.get()?.onProductFetched(remoteProductId) ?: toRemove.add(weakReference)
}
// Remove the collected references
observers.removeAll(toRemove)
}
}
}
Expand Down
Loading