androidMain.net.humans.kmm.mvi.ScanObserver.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mvi-core Show documentation
Show all versions of mvi-core Show documentation
Simple and concise implementation of Redux/MVI approach by Humans.
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)
}
}