Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a observable List in kotlin

Tags:

android

kotlin

I want to update my text whenever there is a new element added to my list.. I tried to do this by below code..

var myList: MutableList<ArrayList<String>> by Delegates.observable(mutableListOf(), onChange = { _, _, new ->
    Constants.debug("Value Changed")
})

But it doesn't seem to work.. Any ideas?

like image 683
Audi Avatar asked Oct 13 '17 10:10

Audi


People also ask

How do you make an observable list?

Creating and using ObservableList The most common way to create it is using observableArrayList() function. ObservableList<String> listInstance = FXCollections. observableArrayList(); //Add a single entry listInstance. add("Java"); System.

What is an observable list?

ObservableList: A list that allows listeners to track changes when they occur.

What is kotlin observable?

Observability refers to the capability of an object to notify others about changes in its data. The Data Binding Library allows you to make objects, fields, or collections observable.


1 Answers

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.

like image 61
Robin Avatar answered Sep 19 '22 05:09

Robin