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

androidMain.net.humans.kmm.mvi.ScanObserver.kt Maven / Gradle / Ivy

The newest version!
@file:Suppress("DeprecatedCallableAddReplaceWith")

package net.humans.kmm.mvi

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.coroutineScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.launch

/**
 * Observer that provides also a previous value
 */
@Suppress("FunctionName")
@Deprecated("Use StateFlow instead of LiveData")
inline fun  ScanObserver(
    crossinline onChanged: (prev: State?, curr: State) -> Unit
): Observer {
    return object : Observer {
        var prev: State? = null
        override fun onChanged(state: State) {
            onChanged.invoke(prev, state)
            prev = state
        }
    }
}

@Deprecated("Use StateFlow instead of LiveData")
inline fun  LiveData.scanObserve(
    lifecycleOwner: LifecycleOwner,
    crossinline onChanged: (prev: State?, curr: State) -> Unit
): Observer {
    return ScanObserver(onChanged).apply {
        observe(lifecycleOwner, this)
    }
}

@Suppress("FunctionName")
@Deprecated("Use StateFlow instead of LiveData")
fun  SuspendScanObserver(
    scope: CoroutineScope,
    onChanged: suspend (prev: State?, curr: State) -> Unit
): Observer {
    val rendererChannel = scope.actor {
        var prev: State? = null
        for (state in channel) {
            onChanged.invoke(prev, state)
            prev = state
        }
    }
    return Observer { state ->
        if (!rendererChannel.trySend(state).isSuccess) {
            scope.launch { rendererChannel.send(state) }
        }
    }
}

@Deprecated("Use StateFlow instead of LiveData")
fun  LiveData.suspendScanObserve(
    lifecycleOwner: LifecycleOwner,
    onChanged: suspend (prev: State?, curr: State) -> Unit
): Observer {
    return SuspendScanObserver(lifecycleOwner.lifecycle.coroutineScope, onChanged).apply {
        observe(lifecycleOwner, this)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy