From fb41b9fbdb8e298d5cb69168dd53a6945a6348b1 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Sun, 13 Oct 2019 20:04:35 +0200 Subject: Allow to unsubscribe from the ObservableState. --- src/main/kotlin/pl/treksoft/kvision/state/ObservableList.kt | 5 ++++- src/main/kotlin/pl/treksoft/kvision/state/ObservableState.kt | 2 +- src/main/kotlin/pl/treksoft/kvision/state/StateBinding.kt | 9 ++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) (limited to 'src/main/kotlin/pl/treksoft/kvision') diff --git a/src/main/kotlin/pl/treksoft/kvision/state/ObservableList.kt b/src/main/kotlin/pl/treksoft/kvision/state/ObservableList.kt index 92109814..7d41e05c 100644 --- a/src/main/kotlin/pl/treksoft/kvision/state/ObservableList.kt +++ b/src/main/kotlin/pl/treksoft/kvision/state/ObservableList.kt @@ -35,9 +35,12 @@ interface ObservableList : MutableList, ObservableState> { class ObservableListWrapper(val mutableList: MutableList = mutableListOf()) : MutableList, ObservableList, ObservableState> { - override fun subscribe(observer: (List) -> Unit) { + override fun subscribe(observer: (List) -> Unit): () -> Unit { onUpdate += observer observer(this) + return { + onUpdate -= observer + } } override val onUpdate: MutableCollection<(MutableList) -> Unit> = mutableListOf() diff --git a/src/main/kotlin/pl/treksoft/kvision/state/ObservableState.kt b/src/main/kotlin/pl/treksoft/kvision/state/ObservableState.kt index 9dc9af0d..f1cba7f0 100644 --- a/src/main/kotlin/pl/treksoft/kvision/state/ObservableState.kt +++ b/src/main/kotlin/pl/treksoft/kvision/state/ObservableState.kt @@ -28,5 +28,5 @@ interface ObservableState { /** * Subscribe for the state change notifications. */ - fun subscribe(observer: (S) -> Unit) + fun subscribe(observer: (S) -> Unit): () -> Unit } diff --git a/src/main/kotlin/pl/treksoft/kvision/state/StateBinding.kt b/src/main/kotlin/pl/treksoft/kvision/state/StateBinding.kt index 7df82adc..adb7d3be 100644 --- a/src/main/kotlin/pl/treksoft/kvision/state/StateBinding.kt +++ b/src/main/kotlin/pl/treksoft/kvision/state/StateBinding.kt @@ -22,8 +22,10 @@ class StateBinding( private val factory: (CONT.(S) -> CONTENT) ) : Widget(setOf()) { + private val unsubscribe: () -> Unit + init { - observableState.subscribe { update(it) } + unsubscribe = observableState.subscribe { update(it) } } private var updateState: ((S, CONTENT) -> Unit)? = null @@ -51,6 +53,11 @@ class StateBinding( this.updateState = updateState } + override fun dispose() { + unsubscribe() + super.dispose() + } + companion object { /** * DSL builder extension function. -- cgit