简体   繁体   中英

How to use flatMapMerge from kotlin flow?

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()?

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-merge.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM