From 76cec0469ff8de4b4cc35136e38d097e483bbddb Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Tue, 30 May 2023 20:23:43 +0300 Subject: [PATCH] add useProperty subscription --- .../controls/spec/DevicePropertySpec.kt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/controls-core/src/commonMain/kotlin/space/kscience/controls/spec/DevicePropertySpec.kt b/controls-core/src/commonMain/kotlin/space/kscience/controls/spec/DevicePropertySpec.kt index ce83edc..cf8c741 100644 --- a/controls-core/src/commonMain/kotlin/space/kscience/controls/spec/DevicePropertySpec.kt +++ b/controls-core/src/commonMain/kotlin/space/kscience/controls/spec/DevicePropertySpec.kt @@ -126,6 +126,25 @@ public fun D.onPropertyChange( } }.launchIn(this) +/** + * Call [callback] on initial property value and each value change + */ +public fun D.useProperty( + spec: DevicePropertySpec, + callback: suspend (T) -> Unit, +): Job = launch { + callback(read(spec)) + messageFlow + .filterIsInstance() + .filter { it.property == spec.name } + .collect { change -> + val newValue = spec.converter.metaToObject(change.value) + if (newValue != null) { + callback(newValue) + } + } +} + /** * Reset the logical state of a property