Skip to content

Instantly share code, notes, and snippets.

@motorro
Created July 31, 2022 16:03
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 motorro/746655909cb28b7fd1df8fff41c59a62 to your computer and use it in GitHub Desktop.
Save motorro/746655909cb28b7fd1df8fff41c59a62 to your computer and use it in GitHub Desktop.
Item loading state
class LoadingState(
@get:VisibleForTesting val id: ItemId,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) : CoroutineState<LceGesture, LceUiState>() {
override fun doStart() {
setUiState(LceUiState.Loading)
load()
}
private fun load() {
stateScope.launch(defaultDispatcher) {
delay(1000L)
withContext(Dispatchers.Main) {
when (id) {
ItemId.LOADS_CONTENT -> toContent()
ItemId.FAILS_WITH_ERROR -> toError()
}
}
}
}
private fun toContent() {
setMachineState(ContentState("Some item data..."))
}
private fun toError() {
setMachineState(ErrorState(id, IOException("Failed to load item")))
}
override fun doProcess(gesture: LceGesture) = when(gesture) {
LceGesture.Back -> onBack()
else -> Timber.d("Unhandled gesture: %s", gesture)
}
private fun onBack() {
setMachineState(ItemListState())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment