Skip to content

Instantly share code, notes, and snippets.

@mattmook
Created July 14, 2021 10:49
Show Gist options
  • Save mattmook/3e59b7348c6a8c2278d0135adf5f73a1 to your computer and use it in GitHub Desktop.
Save mattmook/3e59b7348c6a8c2278d0135adf5f73a1 to your computer and use it in GitHub Desktop.
The state of MVI on Android - ReduxKotlin - PostDetailsViewModel
class PostDetailsViewModel(
private val postRepository: PostRepository,
private val postOverview: PostOverview
) : ViewModel() {
private val detailsMiddleware = middleware<PostDetailState> { store, next, action ->
when (action) {
is ActionTypes.INIT -> store.dispatch(loadDetails(postOverview.id))
else -> next(action)
}
}
private val detailsReducer: Reducer<PostDetailState> = { state, action ->
when (action) {
is PostDetailAction.DataSuccess -> PostDetailState.Details(state.postOverview, action.post)
PostDetailAction.DataFailure -> PostDetailState.NoDetailsAvailable(state.postOverview)
else -> state
}
}
fun loadDetails(id: Int): Thunk<PostDetailState> = { dispatch, _, _ ->
viewModelScope.launch {
when (val status = postRepository.getDetail(id)) {
is Status.Success -> dispatch(PostDetailAction.DataSuccess(status.data))
is Status.Failure -> dispatch(PostDetailAction.DataFailure)
}
}
}
val store = createThreadSafeStore(
reducer = detailsReducer,
preloadedState = PostDetailState.NoDetailsAvailable(postOverview),
enhancer = applyMiddleware(createThunkMiddleware(), detailsMiddleware)
)
init {
// supposed to trigger automatically
store.dispatch(ActionTypes.INIT)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment