Home > Software engineering >  How to get list flow from var list or a mutable list
How to get list flow from var list or a mutable list

Time:10-11

I want a flow that'll emit a Flow<List<T>> when the list updates/changes.

Case 1:

var l = listOf(1, 2, 3, 5)

val listFlowOfInt : Flow<List<Int>> = // A flow which will notify All subscribers (emit value) when l is re-assigned,
//say l= listOf(6,7,8), elsewhere in the code.

Or, Case 2:

val l = mutableListOf(1, 2, 3, 5)

val listFlowOfInt : Flow<List<Int>> = // A flow which will notify All subscribers (emit value) when l is changed,
//say l.add(6), elsewhere in the code.

CodePudding user response:

For the first case it can be achieved using a setter for variable l and MutableStateFlow to notify subscribers:

val listFlowOfInt = MutableStateFlow<List<Int>>(emptyList())
var l: List<Int> = listOf(1, 2, 3, 5)
    set(value) {
        field = value
        listFlowOfInt.value = value
    }

For the second case you can apply the first solution, e.g.:

fun addValueToList(value: Int) {
    // reasigning a list to `l`, the setter will be called.
    l = l.toMutableList().apply { 
        add(value)
    }
}
  • Related