freeletics / FlowRedux

Kotlin Multiplatform Statemachine library with nice DSL based on Flow from Kotlin Coroutine's.

Home Page:https://freeletics.github.io/FlowRedux/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to access previous state using DSL?

mochadwi opened this issue · comments

Current usecase:

Similar approach to fetch github user list, but with search query.

sealed interface MainState {
    object Loading : MainState
    data class Content(val items: List<String> = emptyList()) : MainState
    data class Error(val throwable: Throwable) : MainState
    data class NotFound(val message: String) : MainState
}

sealed interface MainAction {
    data class FindUsers(val newUsername: String) : MainAction
}

our statemachine

class MainStateMachine(
    private val searchUsersUseCase: SearchUsersUseCase,
) : FlowReduxStateMachine<MainState, MainAction>(initialState = MainState.Content()) {
    init {
        spec {
            inState<MainState.Content> {
                on<MainAction.FindUsers> { action, state ->
                    state.override { MainState.Loading }
                    try {
                        val result = searchUsersUseCase.findByUsername(action.newUsername).toList()
                        state.override { MainState.Content(items = result) }
                    } catch (e: Throwable) {
                        state.override { MainState.Error(e) }
                    }
                }
            }

            inState<MainState.Error> {
                // on Retry, access previous state(?) to obtain current username query
            }
        }
    }

    private suspend fun searchUser(
        action: MainAction.FindUsers,
        state: State<MainState.Content>,
    ): ChangedState<MainState> = TODO("implement later")

    private suspend fun loadMoreUser(): ChangedState<MainState> = TODO("implement later")

    private suspend fun retrySearchUser(): ChangedState<MainState> = TODO("implement later")
}

Any suggestion how to model the Retry Action for above requirement? Is it possible to access previous state before error happened, as it requires the username query to execute the gitub APIs

You can add username field to Error

data class Error(val throwable: Throwable, val username: String) : MainState

niceee, really appreciate it! I also agreed with the similar approach. I tho' there's an equivalent DSL publicly for accessing previous state.