kotlin协程,定期发出数据并检查订阅者数量

kotlin coroutine, periodically emit data and check subscriber count

我的服务器在 spring 启动时带有 rSocket 服务:

@MessageMapping("get-messages")
fun getMessageById(): Flow<Set<Message>> {
    return flow { emit(service.getLatestMessages()) }
}

因为 repo 不是反应性的,我想定期去数据库获取数据并将其提供给订阅者(如果存在)。

我想像这样使用 StateFlow:

private val stateFlowMessages = MutableStateFlow<Set<Message>>(emptySet())
init {
    CoroutineScope(Dispatchers.IO).launch {
        while(true){
            if (stateFlowProducts.subscriptionCount.value > 0) 
                stateFlowProducts.value = service.getLatestMessages()
            delay(6 * 1000)
        }
    }
}

但订阅者总是 0,我认为“while”和“delay”不是最佳做法?

0. subscriptionCount: `0       1      2     0     2`
1. Map to true/false: `false  true  true false true`
2. Distinct.        : `false  true       false true`
3. Filter.          : `       true             true`
3. MapLatest.       : `         list             list`.
stateFlowProducts.subscriptionCount
 .map { it > 0 }
 .distinctUntilChanged()
 .filter { it }
 .mapLatest { service.getLatestMessages() }
 .onEach { stateFlowProducts.value = it }
 .launchIn(scope)

https://pl.kotl.in/nQBp0zW6s