Android Studio 在< Item>< Item>AndroidKotlin中从Flow&lt;List &gt;过滤

v9tzhpje  于 2023-08-07  发布在  Android
关注(0)|答案(1)|浏览(111)

我有一个名为Item的数据类。在我的viewmodel中,我有一个Flow,它从Roomdb中获取项目列表。在此程序中,当用户在Textfield中输入一些文本时,将调用onSearchTextChange。在键入一些文本时,我希望在UI列表字段中仅显示那些与输入文本的firstName或middleName或lastName匹配的列表项。我该如何实现这一点?

data class Item(
    @PrimaryKey
    val id: Int? = null,
    val firstName: String,
    val middleName: String,
    val lastName: String,
}

class ItemListViewModel @Inject constructor(
    private val repository: ItemRepository
): ViewModel() {

    var itemList: Flow<List<Item>> = repository.getAllItem()
    private val _searchText = MutableStateFlow("")
    val searchText: StateFlow<String> = _searchText.asStateFlow()

    fun onSearchTextChange(text: String){

        _searchText.value = text                
        if (_searchText.value.isNotEmpty() && _searchText.value.isNotBlank()) {                    
            itemList = itemList.onEach { list ->
                list.filter {
                    it.queryName(text)
                }
            }
        } else{
            itemList= repository.getAllItem()
        }
    }
}

字符串

ctehm74n

ctehm74n1#

可以使用flatMatLatest

class ItemListViewModel @Inject constructor(
    private val repository: ItemRepository
): ViewModel() {
    @OptIn(ExperimentalCoroutinesApi::class)
    val itemList: Flow<List<Item>> = searchText.flatMapConcat { text ->
        if (text.isNotBlank()) {
            repository.getAllItem().onEach { list -> list.filter { /* filter predicate */ } }
        } else {
            repository.getAllItem()
        }
    }

    private val _searchText = MutableStateFlow("")
    val searchText: StateFlow<String> = _searchText.asStateFlow()

    fun onSearchTextChange(text: String){
        _searchText.update { text }
    }
}

字符串

相关问题