pjoter
pjoter

Reputation: 173

Binding LongProperty to internal changes of ListProperty

I have got three classes:

class A { 
    //Duration in seconds
    private val durationProperty = SimpleLongProperty(300)
    var duration by durationProperty
}
class B(list: List<A>) {
    private val aClassesProperty = SimpleListProperty(list.observable())
    val aClasses by aClassesProperty
}
class C(classB: B, repetitions: Int){
    private val bClassProperty = SimpleObjectProperty(classB)

    private val repetitionsProperty = SimpleIntProperty(repetitions)
    val repetitions by repetitionsProperty
}

Now I would like, to create and bind durationProperty inside class B as sum of class A durationProperty (which will be sensitive to adding new class A instance into list and changing any duration of already present instance) and similarly in class C - durationProperty as duration of classB multiplied by repetitions.

Upvotes: 0

Views: 70

Answers (2)

pjoter
pjoter

Reputation: 173

SephB's solution is correct, but finally I used one from there. I found it a little bit more elastic even though there is a lot of boilerplate.

Upvotes: 0

SephB
SephB

Reputation: 627

I don't know kotlin, but the answer should be easy to translate.

You need to use an 'extractor' to handle this, using:

FXCollections#observableArrayList(Callback<E, Observable[]> extractor)

Like:

ObservableList<A> list = FXCollections.observableArrayList(item -> new Observable[] {item.durationProperty});

list.addListener((InvalidationListener) observable -> {
    //Update you sum here
});

The extractor causes any changes to the given observable array of each item in the list to trigger both the InvalidationListener and ListChangeListener of the list to be fired.

Upvotes: 2

Related Questions