I have a MutableList of "DisplayableMessage" unmanaged objects, and I want to find an object from this MutableList by property "messageId".
The code is in onBindViewHolder of a RecyclerViewAdapter:
val displayableMessage = displayableMessages?.find { item -> item?.messageId == message.id }
When the main thread is running this line of code, The exception "java.util.ConcurrentModificationException" is raised.
The last 5 line of stack:
at java.util.ArrayList$Itr.next(ArrayList.java:860)
at MessagesAdapter.onBindViewHolder(MessagesAdapter.kt:279)
at MessagesAdapter.onBindViewHolder(MessagesAdapter.kt:81)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7059)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7101)
MessagesAdapter.kt:279 is the code that I mentioned above.
As you see I'm not removing the list object nor touching the original list.
Edit v1: displayableMessages is referencing a mutable list that is created from detached realm results (This creation happens in another thread).
The code for detaching realm results:
val copiedMessages = Realm.getDefaultInstance().copyFromRealm(realmResults)
After this code, MutableList "list" is created from copiedMessages in another thread (because it includes reading from DB) and then displayableMessages is set to "list".
Then I use the main thread to notify that dataset was changed:
GlobalScope.launch(Dispatchers.Main) {
notifyDataSetChanged()
}
All these codes are run every time realmResults changes.