Skip to content
chirill-kirkinPublic

About

ChElm is a Kotlin Multiplatform UDF-architecture based on The Elm architecture (aka MVU, Model-View-Update).

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ChElm

Maven Central License: MIT

🚧 Work in progress

ChElm (Ch[irkin]Elm) is a Kotlin Multiplatform UDF-architecture based on The Elm architecture (aka MVU, Model-View-Update). All state changes happen in one pure function, and side effects are described as data and executed separately.

Artifacts

Usage

Counter with a command
data class CounterState(val count: Int = 0, val isLoading: Boolean = false)

sealed interface CounterMessage {
  data object Increment : CounterMessage

  data object Reload : CounterMessage

  data class CountLoaded(val count: Int) : CounterMessage
}

sealed interface CounterCommand {
  data object LoadCount : CounterCommand
}

val counterUpdate: Update<CounterMessage, CounterState, CounterCommand> = { message, state ->
  when (message) {
    CounterMessage.Increment -> state.copy(count = state.count + 1).only()
    CounterMessage.Reload -> state.copy(isLoading = true) andCommand CounterCommand.LoadCount
    is CounterMessage.CountLoaded -> state.copy(count = message.count, isLoading = false).only()
  }
}

fun counterCommandExecutor(repository: CounterRepository): CommandExecutor<CounterCommand, CounterMessage> =
  { command ->
    when (command) {
      CounterCommand.LoadCount -> flow { emit(CounterMessage.CountLoaded(repository.loadCount())) }
    }
  }

val store = MVUStore(
  initialState = CounterState(),
  update = counterUpdate,
  commandExecutor = counterCommandExecutor(repository),
)

store.launchIn(scope)
store.send(CounterMessage.Reload)

The UI renders store.state and observes store.commands, for example for navigation.

Saved state

ViewModel with a serializable state
@Serializable
data class EditorState(val title: String = "", val body: String = "")

class EditorViewModel(savedStateHandle: SavedStateHandle) :
  ViewModel(),
  SavedStateMVU<EditorMessage, EditorState, EditorCommand> by savedStateHandle.mvuStore(
    initialState = EditorState(),
    update = editorUpdate,
    commandExecutor = editorCommandExecutor,
    serializer = EditorState.serializer(),
    stateKey = "editor_state",
  ) {
  init {
    launchIn(viewModelScope)
  }
}

To persist only part of the state, use the overload with saveState and restoreState.

Samples

Agent skills

skills contains instructions for coding agents: mvu for the core architecture and android-mvu for Android features.

About

ChElm is a Kotlin Multiplatform UDF-architecture based on The Elm architecture (aka MVU, Model-View-Update).

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages