MicroUtils/coroutines/compose/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/compose/FlowState.kt

47 lines
1.4 KiB
Kotlin
Raw Normal View History

2023-11-29 17:54:27 +00:00
package dev.inmo.micro_utils.coroutines.compose
import androidx.compose.runtime.MutableState
import dev.inmo.micro_utils.coroutines.SpecialMutableStateFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
2023-11-29 19:27:14 +00:00
/**
* This type works like [MutableState], [kotlinx.coroutines.flow.StateFlow] and [kotlinx.coroutines.flow.MutableSharedFlow].
* Based on [SpecialMutableStateFlow]
*/
2023-12-04 09:08:52 +00:00
@Deprecated("Will be removed soon")
2023-11-29 17:54:27 +00:00
class FlowState<T>(
2023-11-29 19:05:01 +00:00
initial: T,
2023-11-29 19:22:43 +00:00
internalScope: CoroutineScope = CoroutineScope(Dispatchers.Default)
2023-11-29 17:54:27 +00:00
) : MutableState<T>,
2023-11-29 19:22:43 +00:00
SpecialMutableStateFlow<T>(initial, internalScope) {
2023-11-29 19:05:01 +00:00
private var internalValue: T = initial
2023-11-29 17:54:27 +00:00
override var value: T
2023-11-29 19:05:01 +00:00
get() = internalValue
2023-11-29 17:54:27 +00:00
set(value) {
2023-11-29 19:05:01 +00:00
internalValue = value
2023-11-29 17:54:27 +00:00
tryEmit(value)
}
override fun onChangeWithoutSync(value: T) {
2023-11-29 19:05:01 +00:00
internalValue = value
super.onChangeWithoutSync(value)
2023-11-29 19:05:01 +00:00
}
2023-11-29 17:54:27 +00:00
2023-11-29 19:05:01 +00:00
override fun component1(): T = value
2023-11-29 17:54:27 +00:00
2023-11-29 19:05:01 +00:00
override fun component2(): (T) -> Unit = { tryEmit(it) }
2023-11-29 17:54:27 +00:00
2023-11-29 19:05:01 +00:00
override fun tryEmit(value: T): Boolean {
internalValue = value
return super.tryEmit(value)
}
2023-11-29 17:54:27 +00:00
2023-11-29 19:05:01 +00:00
override suspend fun emit(value: T) {
internalValue = value
super.emit(value)
2023-11-29 17:54:27 +00:00
}
}
2023-11-29 19:05:01 +00:00
//fun <T> MutableState<T>.asFlowState(scope: CoroutineScope = CoroutineScope(Dispatchers.Main)) = FlowState(this, scope)