Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created July 17, 2019 14:32
Show Gist options
  • Save PaulWoitaschek/f70dd8a8dbb2807bc1da84e8d2dd270c to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/f70dd8a8dbb2807bc1da84e8d2dd270c to your computer and use it in GitHub Desktop.
@file:Suppress("EXPERIMENTAL_API_USAGE")
package my.something.t
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.take
import kotlinx.io.IOException
data class ViewState(val content: String?, val loading: Boolean, val showError: Boolean)
fun contentFlow(): Flow<String> {
return flow {
var index = 0
while (true) {
index++
if (index == 10) {
throw IOException()
}
delay(250)
emit(index.toString())
}
}
}
fun viewState(repeat: Flow<Unit>): Flow<ViewState> {
val initialState = ViewState(content = null, loading = true, showError = false)
return flow {
emit(initialState)
var lastState = initialState
suspend fun updateAndEmit(update: ViewState.() -> ViewState) {
lastState = update(lastState)
emit(lastState)
}
suspend fun startContentFlow() {
try {
contentFlow().collect {
updateAndEmit { copy(content = it, loading = false) }
}
} catch (t: IOException) {
updateAndEmit { copy(loading = false, showError = true) }
repeat.take(1).collect {
updateAndEmit { copy(loading = true, showError = false) }
startContentFlow()
}
}
}
startContentFlow()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment