Skip to content

Commit

Permalink
[FEAT] Create base viewmodel, action and state abstractions
Browse files Browse the repository at this point in the history
  • Loading branch information
peterkrauz committed Sep 23, 2020
1 parent 6383b87 commit a22875c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,26 @@ package com.peterkrauz.grimoire.common
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlin.properties.Delegates
import kotlin.reflect.KProperty

class BaseViewModel<S : BaseViewState, A : BaseViewAction>(state: S) : ViewModel() {
abstract class BaseViewModel<out S : BaseViewState, A : BaseViewAction>(state: S) : ViewModel() {

private var state by Delegates.observable(state, ::onStateChanged)

private val _stateLiveData = MutableLiveData<S>()
val stateLiveData: LiveData<S>
val stateLiveData: LiveData<out S>
get() = _stateLiveData

fun putState(state: S) {
_stateLiveData.postValue(state)
fun performAction(action: A) {
state = reduceState(action)
}

abstract fun loadData()

protected abstract fun reduceState(action: A): S

private fun onStateChanged(property: KProperty<*>, oldState: S, newState: S) {
_stateLiveData.postValue(newState)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.peterkrauz.grimoire.common

interface BaseViewState

object Loading : BaseViewState
interface BaseViewState {
object Loading : BaseViewState
}

0 comments on commit a22875c

Please sign in to comment.