Search code examples
javakotlinlistenerconcurrentmodification

What is the most elegant way to remove a listener from a list from a callback


Suppose I have the following listener

interface MyListener {
    fun onResult(result: Int)
}

and that my class holds a list of this listener

val MyListenerList = ArrayList<MyListener>()

My doubt is: if someone that registered the listener wants to unregister it (remove it from the list) when the callback (onResult) is fired, what is the most elegant way to do it, having in mind that calling it directly while the list iteration is running will cause a ConcurrentModificationException?


Solution

  • Don't iterate over MyListenerList, make a copy of MyListenerList and iterate over the copy. That way the removal can occur on MyListenerList without causing a ConcurrentModificationException.

    For example:

    ArrayList(MyListenerList).forEach { it.onRemove(n) }
    

    or

    MyListenerList.toArray().forEach { it.onRemove(n) }