Skip to content

Instantly share code, notes, and snippets.

@bloderxd
Last active October 31, 2019 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloderxd/830e92702b92c4cf0906c57e54726e14 to your computer and use it in GitHub Desktop.
Save bloderxd/830e92702b92c4cf0906c57e54726e14 to your computer and use it in GitHub Desktop.
sealed class HomeActions {
class ShowPosts(val posts: List<Post>) : HomeActions()
class ShowUsers(val users: List<User>) : HomeActions()
}
data class HomeState(val posts: List<Post> = listOf(), val user: List<User> = listOf())
private val homeActions: ConflatedBroadcastChannel<HomeActions> by lazy { ConflatedBroadcastChannel<HomeActions>() }
private val homeState: Flow<HomeState> by lazy { homeActions.asFlow().asStateMachine(
HomeState(),
{ state, action -> when(action) {
is HomeActions.ShowPosts -> HomeState(posts = action.posts)
is HomeActions.ShowUsers -> HomeState(user = action.users)
else -> state
}}
)}
private fun observeStates() = homeState.collect {
render(it) // <-- this part is not supported by Android, Compose comes to support it
}
private fun fetchPosts() = launch {
val posts = withContext(Dispatchers.IO) {
interactor.fetchPosts()
}
homeActions.send(HomeActions.ShowPosts(posts))
}
private fun fetchUsers() = launch {
val users = withContext(Dispatchers.IO) {
interactor.fetchUsers()
}
homeActions.send(HomeActions.ShowUsers(users))
}
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
typealias Reducer<S, A> = (S, A) -> S
@ExperimentalCoroutinesApi
fun <S, A> Flow<A>.asStateMachine(
initialState: S,
reducer: Reducer<S, A>
): Flow<S> = flow {
var reducers = reducer
var state = initialState
val mutex = Mutex()
collect { action ->
mutex.lock()
state = reducers(state, action)
mutex.unlock()
emit(state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment