Reputation: 1139
val persons = MutableStateFlow<List<Person>>(emptyList())
val names = MutableStateFlow<List<String>>(emptyList())
I want to update names
whenever persons
emits a new value.
This could be done by observing persons
like:
viewModelScope.launch{
persons.collectLatest{personList->
names.emit(personList.map{it.name})
}
}
but I was wondering if there is another way to achieve that, e.g. using flow operators ?
Upvotes: 0
Views: 105
Reputation: 44
Looks a little nicer
persons.map{ persons ->
names.emit(persons.map{ it.name })
}.launchIn(viewModelScope)
If there is no need for reactive actions, then a function can be used.
val names = {
persons.map{
it.name
}
}
// call
println(names())
If it's a class property, even better
val names: String
get() = persons.map{it.name}
Upvotes: 1