首页 > 解决方案 > 用于 MutableStateFlow 的 Android“Transformations.map()”

问题描述

为了实现与Transformation.map()on相同的功能StateFlow,我使用以下代码,它工作正常:

val menuCategoryNames = _menuCategories.mapLatest { menuCategories ->
    menuCategories.map { "${it.name}" }
}.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())

但它看起来很难看,有什么办法让它更易读、更优雅?

标签: androidkotlinkotlin-coroutineskotlin-flowkotlin-stateflow

解决方案


我为这种情况创建了以下扩展:

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())

推荐阅读