unicorn
2.2.0indexedA domain-specific language for creating state machines utilizing reactive sources, enabling streamlined state transitions and actions based on data flows.
11
Stars
—
Used by
dependents
—
Health
/ 100
A domain-specific language for creating state machines utilizing reactive sources, enabling streamlined state transitions and actions based on data flows.
A DSL for state machines based on reactive sources
🚧 Section is under construction 🚧
data class State(
val name: String,
val totalPrice: Int,
)
val namesSource = flowOf("Jacob", "Wacob", "Petrob")
val pricesSource = flowOf(160, 170, 115)
val m = machine<State> {
onEach(namesSource) {
transitionTo { state, name ->
state.copy(name = name)
}
action { _, _, name ->
println("received $name")
}
}
onEach(pricesSource) {
transitionTo { state, price ->
state.copy(totalPrice = price + state.price)
}
}
}
fun main() {
runBlocking {
m.states.collect { "state was updated to $it" }
}
}
The library is available on Maven Central:
implementation "ru.dimsuz:unicorn2:2.1.0"
Copyright 2021 Dmitry Suzdalev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance the License.
You may obtain a copy of the License at
http:
Unless applicable law agreed to writing, software
distributed under the License distributed an BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
See the License the specific language governing permissions
limitations under the License.
sealed class ViewState {
object Loading : ViewState()
data class Error(val text: String): ViewState()
data class Content(val title: String, val subtitle: String) : ViewState()
}
val contentSource = flowOf("Hello" to "World")
val errorSource = emptyFlow<Throwable>() // empty... for now... ;)
val niceThingsSource = flowOf("Friends", "Trees", "Sky")
val screenMachine = machine<ViewState> {
initial = ViewState.Loading to { /* no initial action */ }
whenIn<ViewState.Loading> {
onEach(contentSource) {
transitionTo { state, (title, subtitle) ->
ViewState.Content(title, subtitle)
}
action {
// analytics.record("received content")
}
}
onEach(errorSource) {
transitionTo { state, error ->
ViewState.Error(error.message ?: "unknown error")
}
action { state, newState, error ->
error.printStackTrace()
}
}
}
whenIn<ViewState.Content> {
onEach(niceThingsSource) {
transitionTo { state, thing ->
state.copy(subtitle = thing)
}
}
}
whenIn<ViewState.Error> {
// onEach(retryClicks) { /* configuration of recover transition */ }
}
}
fun main() {
runBlocking {
screenMachine.states.collect(::render)
}
}
Surfaced from shared tags and platforms — no rankings paid for.