234
234

Reputation: 49

how do i observe changes made to kotlin's MutableList?

var questionPool: MutableList<String> = mutableListOf()

questionPool contains string ids.
ids are added and removed throughout the application's lifecycle.

How can i execute a function foo whenever item(s) are added or removed from questionPool?
Is there an observable for mutable lists?

Upvotes: 0

Views: 85

Answers (1)

broot
broot

Reputation: 28452

Most implementations of MutableList are not observable, including the one created with mutableListOf(). We need to either implement our own mutable list or search for an existing library.

If implementing it by ourselves, we can delegate to a real list to make our code simpler and more flexible:

fun main() {
    val list = mutableListOf<String>().observe { println("changed: ${it.toList()}") }
    list += "hello" // changed: [hello]
    list += "world" // changed: [hello, world]
    list -= "hello" // changed: [world]
}

fun <T> MutableList<T>.observe(onChange: (MutableList<T>) -> Unit) = object : MutableList<T> by this {
    override fun add(element: T) = [email protected](element).also { onChange(this) }
    override fun remove(element: T) = [email protected](element).also { onChange(this) }
}

Please note this is more like an example or proof of concept than the complete implementation. We still need to override more functions than above. Also, it would be probably useful to get information on what exactly changed in the list.

Upvotes: 2

Related Questions