Doru N.
06/17/2022, 2:16 PMclass Repository {
private val idsFlow = MutableStateFlow<List<String>>(emptyList())
fun getMyFlow(): Flow<List<String>> = idsFlow.onSubscription {
if (idsFlow.value.isEmpty() idsFlow.value = getRemoteIds())
}
private suspend fun getRemoteIds(): List<String> {
delay(2_000)
return listOf("1", "2")
}
..
// other functions that can modify myFlow (ie. add / delete / update an item from it)
}
problem is, if multiple collectors are subscribing fast enough, getRemoteData gets called multiple times (which I want to avoid).Sam
06/17/2022, 2:28 PMgetMyGlow
separately? I think maybe you just need to move the onSubscription
so that it gets called once when you create the idsFlow
, rather than calling it every time getMyFlow
is called.Doru N.
06/17/2022, 2:44 PMonSubscription
is called for each collector. (I tested it and getRemoteIds gets called for each collector).Nick Allen
06/17/2022, 9:14 PMshareIn
or stateIn
or you need to launch it yourself.
launch {
idsFlow.subscriptionCount.first { it > 0 }
idsFlow.value = getRemoteIds()
}
I'd be careful of this setup. Nothing stops the list from being edited before the results have loaded. I'd recommend starting out without a value, using a sealed class with a Loading object or just using null to indicate that the real data hasn't arrived yet.