kendhia
kendhia

Reputation: 299

Delegates.observable() is not getting notified when using MutableList

I'm trying to use Delegates.observable() in order to get notified when a change on a MutableList has happened.

val items: MutableList<Item> by Delegates.observable(startingItems) {
        _, old, new ->
        Log.e("observable", "${old.size}  -> ${new.size}")
    }

but nothing is happening whenever i try to remove nor add something to the list. I mean there's no trace of the log in the Logcat as it's supposed to be there.

Upvotes: 4

Views: 2460

Answers (2)

kendhia
kendhia

Reputation: 299

I found the answer to this problem and it's actually 'cuz Delegates.observable() only observes changes to the variable, not to the object stored in that variable.

Upvotes: 2

s1m0nw1
s1m0nw1

Reputation: 81929

The docs state:

Observable

Delegates.observable() takes two arguments: the initial value and a handler for modifications. The handler gets called every time we assign to the property (after the assignment has been performed). It has three parameters: a property being assigned to, the old value and the new one.

In your case, you do not assign to items, you only add to the existing instance. The callback never gets invoked.

Suggestion: Use a mutable property with a read-only List and reassign it when a new element is being added:

var items: List<String> by Delegates.observable(mutableListOf()) { _, old, new ->
    println("changed")
}

//add like this:
user.items += "new val"

The plus operator does not call add on the list but creates a new instance with all old elements plus the new one.

Upvotes: 5

Related Questions