Jan
04/14/2023, 3:28 PMCasey Brooks
04/14/2023, 4:02 PMstateFlow.collect { }
will suspend forever until the collector’s coroutineScope is cancelled. A regular cold flow might be able to better capture the intent of this flow, especially if you only have 1 collector and don’t need the upload URL again after it’s used
That said, you can use transformWhile
to add this kind of “stopping” behavior on top of a StateFlow, but the result is a Flow
not StateFlow
.
public sealed class ResourceLoadingStatus {
public data class InProgress(val progressPercentage: Float) : ResourceLoadingStatus()
public data class Loaded(val url: String) : ResourceLoadingStatus()
}
private val _stateFlow = MutableStateFlow<ResourceLoadingStatus>(ResourceLoadingStatus.InProgress(0f))
public suspend fun loadValue(): Flow<ResourceLoadingStatus> {
return _stateFlow
.asStateFlow()
.transformWhile {
// always emit the value downstream
emit(it)
// after emitting each value, check if we should continue processing more items
val shouldStopProcessing = when (it) {
is ResourceLoadingStatus.InProgress -> false
is ResourceLoadingStatus.Loaded -> false
}
shouldStopProcessing
}
}
rook
04/15/2023, 9:25 AMflowOf
builder to make your flow cold. That way the terminal event is reaching the end of the builder block.