kotlin-coroutines - kotlin 协程,定期发出数据并检查订阅者数量
问题描述
我在 Spring Boot 上有带有 rSocket 服务的服务器:
@MessageMapping("get-messages")
fun getMessageById(): Flow<Set<Message>> {
return flow { emit(service.getLatestMessages()) }
}
因为回购不是反应性的,我想定期去数据库获取数据并将其提供给订阅者(如果存在)。
我想像这样使用 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,我认为“延迟”的“同时”不是最佳做法?
解决方案
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)
推荐阅读
- spring-boot - 无法通过自定义注销处理程序注销
- java - Intellij 和 MVN 之间 Junit 的代码覆盖率不匹配
- time-series - 绘制与 gnuplot 对齐的多个轴
- java - 线程 java.util.NoSuchElementException 中的异常:找不到行
- php - 在另一个查询中使用查询作为 PHP 变量
- linux - 为程序运行禁用 SIGABRT (Valgrind)
- mesh - 在 PyGmsh / Gmsh 中添加内部边界或裂缝
- jquery - 突出显示其值已更新的制表符单元格
- python - Kivy - 我看不到图片
- javascript - 为什么我可以将 es6 导入仅用于生成 commonJS 和 UMD 包的库?