From 8067c5ae27822e019dde8bbba5763e9334a86fb0 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Sat, 5 May 2018 22:39:26 +0200 Subject: Function for observable list synchronization --- src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src/main/kotlin/pl/treksoft') diff --git a/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt b/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt index a1901c35..203fac98 100644 --- a/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt +++ b/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt @@ -23,6 +23,7 @@ package pl.treksoft.kvision.utils +import com.lightningkite.kotlin.observable.list.ObservableList import kotlinx.coroutines.experimental.suspendCancellableCoroutine import org.w3c.files.File import org.w3c.files.FileReader @@ -225,3 +226,21 @@ suspend fun File.getContent(): String = suspendCancellableCoroutine { cont -> } reader.readAsDataURL(this@getContent) } + +/** + * Utility extension function to synchronise elements of the ObservableList. + */ +fun ObservableList.syncWithList(list: List) { + if (list.isEmpty()) { + this.clear() + } else { + for (pos in (this.size - 1) downTo list.size) this.removeAt(pos) + list.forEachIndexed { index, element -> + if (index < this.size) { + if (this[index] != element) this[index] = element + } else { + this.add(element) + } + } + } +} -- cgit