Skip to content

Instantly share code, notes, and snippets.

@LutfiTekin
Last active April 29, 2020 10:36
Show Gist options
  • Save LutfiTekin/0b8822be1cf1cb3280cd258b1337b77e to your computer and use it in GitHub Desktop.
Save LutfiTekin/0b8822be1cf1cb3280cd258b1337b77e to your computer and use it in GitHub Desktop.
Notify observers when list elements changed
import java.util.*
class ObservableList<T>(private val wrapped: MutableList<T>): MutableList<T> by wrapped, Observable() {
override fun add(element: T): Boolean {
if (wrapped.add(element)) {
setChanged()
notifyObservers()
return true
}
return false
}
override fun addAll(elements: Collection<T>): Boolean {
if (wrapped.addAll(elements)){
setChanged()
notifyObservers()
return true
}
return false
}
override fun clear() {
wrapped.clear()
setChanged()
notifyObservers()
}
override fun remove(element: T): Boolean {
if (wrapped.remove(element)){
setChanged()
notifyObservers()
return true
}
return false
}
override fun removeAt(index: Int): T {
setChanged()
notifyObservers()
return wrapped.removeAt(index)
}
override fun removeAll(elements: Collection<T>): Boolean {
if (wrapped.removeAll(elements)){
setChanged()
notifyObservers()
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment