Created
April 15, 2023 18:55
-
-
Save hoc081098/340c0ed61efcbb34b268eed92a7e4710 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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