commonMain.com.arkivanov.decompose.value.operator.Map.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of decompose Show documentation
Show all versions of decompose Show documentation
Kotlin Multiplatform lifecycle-aware business logic components
package com.arkivanov.decompose.value.operator
import com.arkivanov.decompose.Cancellation
import com.arkivanov.decompose.Lock
import com.arkivanov.decompose.synchronized
import com.arkivanov.decompose.value.Value
fun Value.map(mapper: (T) -> R): Value =
MappedValue(this, mapper)
private class MappedValue(
private val upstream: Value,
private val mapper: (T) -> R,
) : Value() {
private val lock = Lock()
private var lastUpstreamValue: T = upstream.value
private var lastMappedValue: R = mapper(lastUpstreamValue)
override val value: R get() = mapCached(upstream.value)
private fun mapCached(value: T): R =
lock.synchronized {
if (value !== lastUpstreamValue) {
lastUpstreamValue = value
lastMappedValue = mapper(value)
}
lastMappedValue
}
override fun subscribe(observer: (R) -> Unit): Cancellation =
upstream.subscribe { observer(mapCached(it)) }
}