All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.arkivanov.decompose.value.operator.Map.kt Maven / Gradle / Ivy

There is a newer version: 3.2.0-beta01
Show newest version
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)) }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy