Reducers reduce the current state and incoming events to produce a new state.
reduce는 새로운 이벤트가 들어오면 새로운 상태를 생산한다고 정의되어 있다.
@OrbitDsl
public suspend fun <S : Any, SE : Any> SimpleSyntax<S, SE>.reduce(reducer: SimpleContext<S>.() -> S) {
containerContext.reduce { reducerState ->
SimpleContext(reducerState).reducer()
}
}
해당 코드는 suspend 함수를 사용하여 코루틴 비동기적으로 실행되고 있다. containerContext 의 프로퍼티인 reduce를 가져와 람다를 열어 상태가 변경될 때, SimpleContext 의 reducer를 호출하여 상태가 바뀜을 함수의 인자로 알려준다.
그렇기 때문에 Orbit DSL인 reduce 를 사용하여 내부 state가 바뀜을 알 수 있는 것이다.
ViewModel 에서 reduce DSL을 사용하면 다음과 같이 상태를 바꿀 수 있다.
// InitViewModel.kt
intent {
reduce {
reduce { state.copy(status = UiStatus.Success) }
}
}
해당 부분 밑에 코드처럼 collectAsState 함수에서 해당 부분의 상태를 받아올 수 있다.
val viewModel = getComposeViewModel<InitViewModel>()
val state by viewModel.collectAsState()
이제 해당 state 는 Compose Component 에서 UiState 클래스를 사용하여 상태관리를 할 수 있다.
InitPage(state = state, onRetry = { viewModel.retry() })