Alexander af Trolle
01/31/2025, 10:29 AM@Rpc
interface MyService : RemoteService {
suspend fun serviceItemsFlow(): Flow<String>
}
@OptIn(ExperimentalCoroutinesApi::class)
fun SharedFlow<MyService?>.mapServiceFlow(): Flow<String> =
flatMapLatest {
channelFlow {
streamScoped {
(it?.serviceItemsFlow() ?: emptyFlow())
.collect {
send(it)
}
}
}
}
Alexander af Trolle
01/31/2025, 10:31 AMAlexander af Trolle
01/31/2025, 11:18 AMwrapInStreamScope
is safe, streamScoped can outlive clients & service.
fun <S, R> Flow<S>.flatMapLatestStreamScoped(
transform: suspend (value: S) -> Flow<R>
): Flow<R> = transformLatest {
streamScoped {
emitAll(transform(it))
}
}
fun <S> Flow<S>.wrapInStreamScope(): Flow<S> = channelFlow {
streamScoped {
collect {
send(it)
}
}
}
If wrapInStreamScope is safe/fine, the would be nice to have this in the library or if we could annotate with something like streamScopedToFlow