Last active
October 31, 2019 14:45
-
-
Save bloderxd/830e92702b92c4cf0906c57e54726e14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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)) | |
} |
This file contains hidden or 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.* | |
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