Skip to content

Instantly share code, notes, and snippets.

@davidec-twinlogix
Last active May 13, 2021 18:50
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 davidec-twinlogix/25abe753277dd8ec985d5098f860fcdc to your computer and use it in GitHub Desktop.
Save davidec-twinlogix/25abe753277dd8ec985d5098f860fcdc to your computer and use it in GitHub Desktop.
UniFlow scenario
class TutorialViewModel : AndroidDataFlow(TutorialState()) {
init {
viewModelScope.launch {
onFlow(
flow = ::secondsFlow,
doAction = {
(this as? TutorialState)?.copy(seconds = it)?.let { state ->
setState { state }
}
}
)
}
}
fun onButtonClick() {
actionOn<TutorialState> { state ->
val clicks = state.clicks + 1
setState { state.copy(loading = true, clicks = clicks) }
}
actionOn<TutorialState> { state ->
val result = getResult(state.clicks)
setState { state.copy(loading = false, result = result) }
}
}
fun onButtonClick2() {
viewModelScope.launch {
val clicks = (getState() as TutorialState).clicks + 1
actionOn<TutorialState> { state ->
setState { state.copy(loading = true, clicks = clicks) }
}
val result = getResult(clicks)
actionOn<TutorialState> { state ->
setState { state.copy(loading = false, result = result) }
}
}
}
data class TutorialState(
val seconds: Int = 0,
val clicks: Int = 0,
val loading: Boolean = false,
val result: String? = null,
) : UIState()
private fun secondsFlow(): Flow<Int> {
return flow {
var t = 0
while (true) {
t++
emit(t)
delay(1000)
}
}
}
private suspend fun getResult(i: Int): String {
delay(3000)
return "result $i"
}
//View
viewModel.states.observeAsState().value?.let { state ->
if (state is TutorialState) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.fillMaxWidth(),
text = "Seconds ${state.seconds}",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "Clicks ${state.clicks}",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "Loading ${state.loading}",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "Result ${state.result}",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
Button(
modifier = Modifier.padding(top = 20.dp),
onClick = viewModel::onButtonClick
) {
Text(text = "GET RESULT")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment