Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Last active April 15, 2023 18:52
Show Gist options
  • Save hoc081098/2c290bcfb73bfebdc6ca7a334f2625c2 to your computer and use it in GitHub Desktop.
Save hoc081098/2c290bcfb73bfebdc6ca7a334f2625c2 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())
typealias Reducer = (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