public Knot<State,Change,Action>
Knot helps managing application state by reacting on events and performing asynchronous
actions in a structured way. There are five core concepts Knot defines: State, Change,
Reducer, class Effect and Action.
State represents an immutable partial state of an Android application. It can be a state of a screen or a state of an internal headless component, like repository.
Change is an immutable data object with an optional payload intended for changing the State.
A Change can be produced from an external event or be a result of execution of an Action.
Action is a synchronous or an asynchronous operation which, when completed, can emit a new Change.
Reducer is a pure function that takes the previous State and a Change as arguments and returns
the new State and an optional Action wrapped by Effect class. Reducer in Knot is designer
to stays side-effects free because each side-effect can be turned into an Action and returned from
Reducer function together with a new State.
class Effect is a convenient wrapper class containing the new State and an optional Action. If
Action is present, Knot will perform it and provide resulting Change back to Reducer.
Example below shows the Knot which is capable of loading data, handling success and failure loading results and reloading data when an external "data changed" signal is received.
val knot = knot {
state {
initial = State.Empty
}
changes {
reduce { change ->
when (change) {
is Change.Load -> State.Loading + Action.Load
is Change.Load.Success -> State.Content(data).only
is Change.Load.Failure -> State.Failed(error).only
}
}
}
actions {
perform { action ->
action
.switchMapSingle { api.load() }
.map { Change.Load.Success(it) }
.onErrorReturn { Change.Load.Failure(it) }
}
}
}
events {
transform {
dataChangeObserver.signal.map { Change.Load }
}
}
watch {
any { println(it) }
}
}
knot.change.accept(Change.Load)
class Effect,
Flowchart diagram,
class Effect| Modifier and Type | Method and Description |
|---|---|
io.reactivex.functions.Consumer<Change> |
getChange() |
io.reactivex.disposables.Disposable |
getDisposable() |
io.reactivex.Observable<State> |
getState() |