Android Kotlin是在列表中切换项目的有效方法

Android Kotlin是在列表中切换项目的有效方法,android,list,kotlin,collections,kotlin-android-extensions,Android,List,Kotlin,Collections,Kotlin Android Extensions,我有一个toggleItem算法,可以从recyclerview项目列表中删除/添加项目。我的一个朋友对它进行了优化,以减少带来的代码气味 我正在寻找替代的/最小的方法来编写这个简单的算法,使用我们拥有的很棒的kotlin collections操作。除了这两种选择,您的最佳/最小选择是什么 (ItemType是一个枚举类,作为初始化项的标记) 原件: fun toggleItem(itemType: ItemType, show: Boolean) { val item =

我有一个toggleItem算法,可以从recyclerview项目列表中删除/添加项目。我的一个朋友对它进行了优化,以减少
带来的代码气味

我正在寻找替代的/最小的方法来编写这个简单的算法,使用我们拥有的很棒的kotlin collections操作。除了这两种选择,您的最佳/最小选择是什么

(ItemType是一个枚举类,作为初始化项的标记)

原件:

fun toggleItem(itemType: ItemType, show: Boolean) {
        val item = _allItems.value?.find { it.type == itemType }
        item?.let {
            if (!show) _carouselItems.value = _carouselItems.value!!.minus(it)
        } ?: if (show) _carouselItems.value = _carouselItems.value!!.plus(item!!)

    }
进一步优化:

fun toggleItem(itemType: ItemType, show: Boolean) {
    if (show) {
        val item = _allItems.value?.find { it.type == itemType }
        item?.let {
            _carouselItems.value = _carouselItems.value?.plus(it)?.distinct()?.sortedBy { it.type }
        }
    } else
        _carouselItems.value = _carouselItems.value?.filter { it.type != itemType }
}

我推断
\u allitem
\u carouselitem
都是
可变livedata
类型或非常类似的类型。您可以替换您的
使用Elvis运算符和默认值,以避免长链的空安全调用。使用空列表表示无数据比使用null更清晰,因此我将使LiveData的类型不可为null

在这种情况下,您可以使用Elvis操作符进行提前返回/智能转换,以避免使用
let
。在我看来,这种方式更具可读性

fun toggleItem(itemType: ItemType, show: Boolean) {
    val currentItems = _carouselItems.value ?: emptyList()
    if (show) {
        val item = _allItems.value?.find { it.type == itemType }
            ?: return
        _carouselItems.value = (currentItems + item).distinct().sortedBy { it.type }
    } else
        _carouselItems.value = currentItems.filter { it.type != itemType }
    }
}
如果您知道该项目应始终位于“所有项目”列表中,则这可能更简洁:

fun toggleItem(itemType: ItemType, show: Boolean) {
    val item = _allItems.value?.find { it.type == itemType }
        ?: return
    val currentItems = _carouselItems.value ?: emptyList()
    _carouselItems.value = when {
            show -> (currentItems + item).distinct().sortedBy { it.type }
            else -> currentItems - item
        }
}

您也可以考虑转换为StaseFLUE。它与LiveData的概念类似,只是它强制一个起始值,因此如果类型不可为null,则其

参数不可为null。但是您应该首先熟悉协同程序的基础知识。

当数据集很小时,这两种方法都可以,但随着数据大小的增加,计算量会迅速增加

//使用ItemType作为键将可见性值存储到地图
val_切换:Map=mapOf(ItemType.One为false,ItemType.Two为true);
趣味切换项(itemType:itemType,show:Boolean){
_切换[项目类型]=显示
val list=_allItem.values?.filter(项->_切换[item.type])?:listOf()
_carouselItems.value=列表
}