Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin watch array change

Tags:

arrays

kotlin

I'm trying to be notified when an array changes its content. Through this code I'm able to notify the setting of the array, but nothing happens when a new item is inserted.

var array: MutableMap<String, List<String>> = mutableMapOf()
    set(value) {
        field = value
        arrayListener?.notify()
    }

The only thing I came up with is resetting the array to itself everytime I add, delete o edit items, like this:

array = array

I read this question How to watch for array changes? relative to Javascript, but I'd like an easier solution then creating a new object, can anyone suggest it?

like image 650
marcolav Avatar asked Oct 14 '25 16:10

marcolav


1 Answers

Array's API is quite simple: elements can be written there and can be read from an array.

At 99% (a number without justification, read "the vast majority") array's usages people are satisfied with this simple API. It would be a shame if a simple interface with straightforward implementation was mixed with tricky functionality.

Moving to your problem, a possible approach could be create an array's wrapper

class ArrayWrapper<T> (private val array: Array<out T>, 
                       private val onChange: () -> Unit) {
    val size = array.size

    fun get(index: Int): T {
        return array[index]
    }

    fun set(index: Int, value: T) {
        array[index] = value
        onChange()
    }
}

An example of usage:

val ints = ArrayWrapper(arrayOf(1, 2, 3)) {
    println("Array has been changed")
}
like image 180
Sergei Voitovich Avatar answered Oct 17 '25 06:10

Sergei Voitovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!