2

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?

Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61

1 Answers1

4

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) }
hudsonb
  • 2,214
  • 19
  • 20
  • Thank you for your reply, @hudsonb. I will just not mark it as correct yet because I wanna check if is there any other elegant way than that. – Augusto Carmo Dec 06 '17 at 16:18
  • 1
    This is how it is commonly supported. Another option you could consider would be to use a `CopyOnWriteArrayList` rather than `ArrayList`. – hudsonb Dec 06 '17 at 19:21