I have a flow collection that I want to do a condition where if the list if empty to just return as there's no further work to be done.
my issue is that Android studio is tossing a nagging message at me
there is more than one label with such a name in this scope
I'm assuming it's upset because I'm doing a collect within a collect (see code below, it'll hopefully make sense why I'm doing that).
is there a way to relabel the collect so it knows which one I'm talking about, I didn't see anything on it.
Also I'm new to flow so if I'm doing this wrong, let me know the proper way as this seems valid as I need one flow for the other one.
viewModelScope.launch {
companyDataStore.getFromDataStore()
.catch { e ->
_snackBar.value = e.message
}.collect { company ->
companyFeatures = company.features
userClient.getGroupsByFeatures(companyFeatures)
.catch { e ->
_snackBar.value = e.message
}
.collect { groupList ->
if (groupList.data?.size == 0)
{
return@collect
}
groups = groupList.data!!
feedFilter.group = groups.firstOrNull()?.guid
}
}
}
CodePudding user response:
You can add labels to the collect
blocks and use them with return
statement:
.collect collectLabel2@ {
// ...
return@collectLabel2
// ...
}
Here label collectLabel2
is added.
To eliminate multiple collect
blocks you can try to use flatMapMerge
or flatMapLatest
function:
viewModelScope.launch {
companyDataStore.getFromDataStore()
.catch { e ->
_snackBar.value = e.message
}
.flatMapMerge { company ->
companyFeatures = company.features
userClient.getGroupsByFeatures(companyFeatures)
.catch { e ->
_snackBar.value = e.message
}
}
.collect { groupList ->
if (groupList.data?.size != 0) {
groups = groupList.data!!
feedFilter.group = groups.firstOrNull()?.guid
}
}
}