How to create a observable List in kotlin

You can use something like this :

class ObservableList<T>(private val wrapped: MutableList<T>): MutableList<T> by wrapped, Observable() {
    override fun add(element: T): Boolean {
        if (wrapped.add(element)) {
            setChanged()
            notifyObservers()
            return true
        }
        return false
    }
}

It doesn't work because the observabe delegate only observes changes to the variable, not to the object stored in that variable. So when the list changes, the variable still points to the same list, and the observable delegate has no idea anything has changed. To observe that, you need some means of actually observing the contents of the list, which is not something Kotlin or Java provides out of the box. You'll need some kind of observable list for that.

Alternatively, you could use a standard list (instead of a mutable one), and whenever you need to change the list, replace it with the new version of the list. This way you can listen to changes just like you want to, but probably need to adjust a lot of other code using that list.

Tags:

Android

Kotlin