I have these piece of code and I want it to make it more optimal
I guess I can use kotlin-flow's flatMapMerge but I don't think how should I convert my code to flow
val quiries = listof("s","b","s","g","d","r","t")
quiries.map { query ->
viewModelScope.launch {
val results = fetchColumns(query)
resultMutableData.postValue(results)
}
}
and fetchColumns() are suspended functions I am thinking maybe I need to have flows of queries ???? what is the way of using flatMapMerge()?
Try using something like this:
listOf("s","b","s","g","d","r","t").asFlow()
.map { fetchColumns(it) }
.onEach { resultMutableData.postValue(it) }
.launchIn(viewModelScope)
Since you don't switch onto another flow, there is no need for any of flatMap*
functions, just map
will be enough. Moreover, map
parameter is already declared as suspend
, so you won't block your thread. But map
operator was designed to process data sequentially, so these transformations won't be run in parallel. To achieve parallel processing, a workaround using flatMapMerge
can be used:
listOf("s","b","s","g","d","r","t").asFlow()
.onEach { println("onEach: $it") }
.flatMapMerge {
flow {
emit(fetchColumns(it))
}
}
.onEach { resultMutableData.postValue(it)) }
.launchIn(viewModelScope)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.