Populate and emit StateFlow List

你。 提交于 2021-01-28 12:13:52

问题


I want to use StateFlow. But for now, I don't find any lecture which could help me.

I'm facing an issue : To start, I have a singleton which hold a list of String, I want something "easy" to understand even if it isn't the goal purpose for now. The purpose is to populate and emit the list with strings (it will be a complex object later).

class CustomStateFlow() {
    private val _custom = MutableStateFlow(emptyList<String>())
    val custom: StateFlow<List<String>> = _custom

    fun addString(string: String) {
        val tempList = _custom.value.toMutableList()
        tempList.add(string)
        _custom.value = tempList
}

This seems to work, but I don't like the temp list... without, I can't trigger the "collect" of custom in my fragment.

Is there a way to achieve this without using a tempList ?

Thanks you


回答1:


If you don't want to take temporary variable in-order to add new item to mutable list you can use plus (+) operator function. By doing so returns you new list (immutable) with added value that you can use further.

So the pseudo-code becomes something like this: val newList = oldMutableList + newItem

Similarly you can remove item from list like val newList = oldMutableList - itemToRemove

Read more about operator function on kotlin collection here!



来源:https://stackoverflow.com/questions/65001729/populate-and-emit-stateflow-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!