Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Created April 15, 2023 18:52
Show Gist options
  • Save hoc081098/c6f8ececb4aa8d9753bd902a918f6083 to your computer and use it in GitHub Desktop.
Save hoc081098/c6f8ececb4aa8d9753bd902a918f6083 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*
data class State(val isLoading: Boolean = false, val items: List<Int> = emptyList())
fun interface Reducer {
operator fun invoke(current: State): State
}
val loadingReducer = Reducer { it.copy(isLoading = true) }
val loadedReducer = Reducer{ it.copy(isLoading = false, items = listOf(1, 2, 3)) }
fun main() = runBlocking {
flowOf<Reducer>(
loadingReducer,
loadedReducer,
loadingReducer
)
.scan(State()) { state, reducer -> reducer(state) }
.collect(::println)
}
// State(isLoading=false, items=[])
// State(isLoading=true, items=[])
// State(isLoading=false, items=[1, 2, 3])
// State(isLoading=true, items=[1, 2, 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment