Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0siara/962ee93bf42431710c8dbff9772bb198 to your computer and use it in GitHub Desktop.
Save k0siara/962ee93bf42431710c8dbff9772bb198 to your computer and use it in GitHub Desktop.
HandleEventsAndStateWithSharedFlowAndStateFlowExample
class AddEmployeeViewModel(
private val employeeRepository: EmployeeRepository
) :
BaseViewModel<AddEmployeeContract.State, AddEmployeeContract.Event, AddEmployeeContract.Effect>(
initialState = AddEmployeeContract.State.Loading()
) {
...
override fun handleEvent(event: AddEmployeeContract.Event) {
when (event) {
is AddEmployeeContract.Event.AddAddressEvent -> {
updateForm(
address = "",
addresses = currentState.addresses.plus(Address(currentState.address))
)
}
is AddEmployeeContract.Event.RemoveAddressEvent -> {
val addresses = currentState.addresses.toMutableList()
addresses.remove(event.address)
updateForm(addresses = addresses)
}
}
}
fun updateForm(
firstName: String? = null,
lastName: String? = null,
address: String? = null,
addresses: List<Address>? = null,
) {
updateUiState {
AddEmployeeContract.State.FormUpdated(
firstName = firstName ?: currentState.firstName,
lastName = lastName ?: currentState.lastName,
address = address ?: currentState.address,
addresses = addresses ?: currentState.addresses
)
}
}
fun onAddAddressClicked() {
setUiEvent(AddEmployeeContract.Event.AddAddressEvent)
}
fun onRemoveAddressClicked(address: Address) {
setUiEvent(AddEmployeeContract.Event.RemoveAddressEvent(address))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment