Skip to content

Instantly share code, notes, and snippets.

@beigirad
Created December 2, 2020 19:16
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 beigirad/5489fe50a5e8226c9d2d93e17050fb9d to your computer and use it in GitHub Desktop.
Save beigirad/5489fe50a5e8226c9d2d93e17050fb9d to your computer and use it in GitHub Desktop.
Single State Pattern
data class StateModel(
val detail: ViewResource<Entity1>,
val something: Entity2?,
val error: Event<String>?
) {
companion object {
val initial = StateModel(
detail = ViewResource.NotAvailable,
something = null,
error = null
)
}
import androidx.annotation.Nullable;
public class Event<T> {
private T content;
private boolean hasBeenHandled = false;
public Event(T content) {
this.content = content;
}
@Nullable
public T getContentIfNotHandled() {
if (hasBeenHandled) {
return null;
} else {
hasBeenHandled = true;
return content;
}
}
public boolean hasBeenHandled() {
return this.hasBeenHandled;
}
@Nullable
public T peekContent() {
return content;
}
public void ifNotHandled(EventHandler<T> eventHandler) {
if (!hasBeenHandled) {
hasBeenHandled = true;
eventHandler.handle(content);
}
}
public interface EventHandler<T> {
void handle(T content);
}
}
private val _state = MutableStateFlow(StateModel.initial)
val state: StateFlow<StateModel> = _state.asStateFlow()
fun getDetail() {
_state.value = _state.value.copy(detail = ViewResource.Loading())
viewModelScope.launch {
when (val result = repository.getDetail(productId)) {
is Either.Success ->
_state.value = _state.value.copy(detail = ViewResource.Ok(result.value))
is Either.Failure ->
_state.value = _state.value.copy(detail = ViewResource.Error(result.message, result.code))
}
}
}
viewModel.state.onEach { state ->
binding.tvName = state.detail.name
binding.progress.isVisiable = state.detail is ViewResource.Loading
state.error?.ifNotHandled(::toast)
}.launchIn(viewLifecycleOwner.lifecycleScope)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment