Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Created April 15, 2023 18:55
Show Gist options
  • Save hoc081098/340c0ed61efcbb34b268eed92a7e4710 to your computer and use it in GitHub Desktop.
Save hoc081098/340c0ed61efcbb34b268eed92a7e4710 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())
sealed interface Reducer {
operator fun invoke(current: State): State
}
object LoadingReducer : Reducer {
override fun invoke(current: State) = current.copy(isLoading = true)
}
object LoadedReducer : Reducer {
override fun invoke(current: State) = current.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