android - 用于 MutableStateFlow 的 Android“Transformations.map()”
问题描述
为了实现与Transformation.map()
on相同的功能StateFlow
,我使用以下代码,它工作正常:
val menuCategoryNames = _menuCategories.mapLatest { menuCategories ->
menuCategories.map { "${it.name}" }
}.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
但它看起来很难看,有什么办法让它更易读、更优雅?
解决方案
我为这种情况创建了以下扩展:
inline fun <T, R> Flow<Iterable<T>>.mapLatestIterable(crossinline transform: (T) -> R): Flow<List<R>> =
mapLatest { it.map(transform) }
你可以像这样使用它:
_menuCategories
.mapLatestIterable { "${it.name}" }
.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
推荐阅读
- azure-data-factory - 监控未显示所有管道运行
- python - 如何在 Python 中将 for 循环转换为带有工作 if 语句的嵌套 while 循环
- python - 密钥错误消息
- python - 使用 Python 更改目录,找不到目录错误
- powershell - 使用 PowerShell 在远程计算机上安装 MSI 文件
- javascript - 如何检查一个充满 Jquery 对象的数组的值
- php - Laravel 验证器正则表达式:以逗号分隔格式验证所有内容
- python - 最近值的 Python 百分位数与先前值的窗口
- javascript - 在Javascript for循环中未存储变量超过一秒钟
- scikit-learn - 如何使用 K 折交叉验证计算准确度和混淆矩阵?