从回调中删除听众的最优雅方法是什么?



假设我有以下侦听器

interface MyListener {
    fun onResult(result: Int)
}

,我的班级列出了此听众的列表

val MyListenerList = ArrayList<MyListener>()

我的疑问是:如果注册听众的人想在回调(onResult)射击时将其取消(将其从列表中删除),那么最优雅的方法是什么,请注意将其直接称为称为在列表迭代运行时,会导致ConcurrentModificationException

不要在 MyListenerList上迭代,制作 MyListenerList的副本并在副本上迭代。这样,可以在MyListenerList上删除而不会引起ConcurrentModificationException

例如:

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

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

相关内容

最新更新