org.kin.sdk.design.viewmodel.tools.ViewModel.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of viewmodel-tools Show documentation
Show all versions of viewmodel-tools Show documentation
Kin Android SDK View Model Tools
package org.kin.sdk.design.viewmodel.tools
typealias StateListener = (StateType) -> Unit
interface ObservableViewModel {
fun addStateUpdateListener(listener: StateListener)
fun removeStateUpdateListener(listener: StateListener)
fun removeAllListeners()
}
interface ViewModel : ObservableViewModel {
fun cleanup()
}
abstract class BaseObservableViewModel : ObservableViewModel {
private var state: StateType? = null
private val listeners = mutableListOf>()
private fun getOrInitState(): StateType {
return state ?: getDefaultState().also {
state = it
onStateUpdated(it)
}
}
final override fun addStateUpdateListener(listener: StateListener) {
listeners.add(listener)
listener(getOrInitState())
}
final override fun removeStateUpdateListener(listener: StateListener) {
listeners.remove(listener)
}
override fun removeAllListeners() {
listeners.clear()
}
protected fun updateState(updater: (previousState: StateType) -> StateType) {
val currentState = getOrInitState()
val updatedState = updater(currentState)
state = updatedState
if (currentState != updatedState) {
listeners.forEach { it(updatedState) }
}
onStateUpdated(updatedState)
}
protected fun withState(withState: StateType.() -> T): T {
return withState(getOrInitState())
}
protected abstract fun getDefaultState(): StateType
open fun onStateUpdated(state: StateType) { }
}
abstract class BaseViewModel(protected val args: ArgsType) : ViewModel, BaseObservableViewModel() {
override fun cleanup() {
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy