2

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.
Sergio
  • 27,326
  • 8
  • 128
  • 149
Cyber Avater
  • 1,494
  • 2
  • 9
  • 25

1 Answers1

2

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)
    }
}
Sergio
  • 27,326
  • 8
  • 128
  • 149