Created
October 18, 2021 15:18
-
-
Save volodymyr-sch/941558d2ebc4fd675c1ecb1baac58f57 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
| @HiltViewModel | |
| class MainViewModel @Inject constructor( | |
| private val getTodos: IGetTodosUseCase, | |
| private val dispatcher: CoroutineDispatcher, | |
| private val viewMapper: MainScreenViewDataMapper, | |
| ) : BaseViewModel<MainScreenState, MainScreenUiEvent>() { | |
| private val reducer = MainReducer(MainScreenState.initial()) | |
| override val state: StateFlow<MainScreenState> | |
| get() = reducer.state | |
| val timeMachine: TimeCapsule<MainScreenState> | |
| get() = reducer.timeCapsule | |
| init { | |
| viewModelScope.launch(dispatcher) { | |
| val data = getTodos.invoke() | |
| sendEvent(MainScreenUiEvent.ShowData(viewMapper.buildScreen(data))) | |
| } | |
| } | |
| private fun sendEvent(event: MainScreenUiEvent) { | |
| reducer.sendEvent(event) | |
| } | |
| fun changeAddDialogState(show: Boolean) { | |
| sendEvent(MainScreenUiEvent.OnChangeDialogState(show)) | |
| } | |
| fun addNewItem(text: String) { | |
| sendEvent(MainScreenUiEvent.AddNewItem(text)) | |
| } | |
| fun onItemCheckedChanged(index: Int, isChecked: Boolean) { | |
| sendEvent(MainScreenUiEvent.OnItemCheckedChanged(index, isChecked)) | |
| } | |
| private class MainReducer(initial: MainScreenState) : Reducer<MainScreenState, MainScreenUiEvent>(initial) { | |
| override fun reduce(oldState: MainScreenState, event: MainScreenUiEvent) { | |
| when (event) { | |
| is MainScreenUiEvent.OnChangeDialogState -> { | |
| setState(oldState.copy(isShowAddDialog = event.show)) | |
| } | |
| is MainScreenUiEvent.ShowData -> { | |
| setState(oldState.copy(isLoading = false, data = event.items)) | |
| } | |
| is MainScreenUiEvent.DismissDialog -> { | |
| setState(oldState.copy(isShowAddDialog = false)) | |
| } | |
| is MainScreenUiEvent.AddNewItem -> { | |
| val newList = oldState.data.toMutableList() | |
| newList.add( | |
| index = oldState.data.size - 1, | |
| element = MainScreenItem.MainScreenTodoItem(false, event.text), | |
| ) | |
| setState(oldState.copy( | |
| data = newList, | |
| isShowAddDialog = false | |
| )) | |
| } | |
| is MainScreenUiEvent.OnItemCheckedChanged -> { | |
| val newList = oldState.data.toMutableList() | |
| newList[event.index] = (newList[event.index] as MainScreenItem.MainScreenTodoItem).copy(isChecked = event.isChecked) | |
| setState(oldState.copy(data = newList)) | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment