I have an overriden function that returns a flow of list and if the condition is not met, I emit an emptyList() to cover up the corner case:
override fun returnFlow(): Flow<List<Item>> {
return combine(booleanFlow()) { items, boolean ->
if (!boolean) {
items
} else {
emptyList()
}
}
}
I want to remove the else {} logic and change it to only emitting a list when boolean is false. Ideally I would like something similar to this:
override fun returnFlow(): Flow<List<Item>> {
return combine(booleanFlow()) { items, boolean ->
while (!boolean) {
items
}
}
}
Can I use something like cancelFlow() or return Nothing?
I tried how to stop Kotlin flow when certain condition occurs and it doesn't work since the return type changes to Flow<Unit>
.
CodePudding user response:
Use combineTransform
instead of combine
. Instead of always emitting the item returned by the lambda, this lets you choose whether or not to emit an item by calling emit
.
override fun returnFlow(): Flow<List<Item>> {
return combineTransform(booleanFlow()) { items, boolean ->
if (!boolean) {
emit(items)
}
}
}