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

org.kin.sdk.design.viewmodel.tools.ViewModel.kt Maven / Gradle / Ivy

There is a newer version: 2.1.2
Show newest version
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