Václav Škorpil
12/12/2021, 7:44 PMclass KeywordService(val keywordRepo: KeywordRepo) {
fun getKeywordData(
keywordId: UUID,
): Flow<String> {
val name = keywordRepo.getKeywordName() // suspend function
return keywordRepo.getKeywordData(name) // function that returns flow
}
}
Currently i am calling it with a flow builder, but i am not sure if this is correct.
class KeywordService(val keywordRepo: KeywordRepo) {
fun getKeywordData(
keywordId: UUID,
): Flow<String> = flow {
val name = keywordRepo.getKeywordName() // suspend function
val dataFlow = keywordRepo.getKeywordData(name) // function that returns flow
emitAll(dataFlow)
}
}
This way it feels little bit clunky, is there any better way to do it?Francesc
12/12/2021, 8:44 PMfun getKeywordData(
keywordId: UUID,
): Flow<String> = flow {
emit(keywordRepo.getKeywordName())
}.flatmapLatest { name ->
keywordRepo.getKeywordData(name)
}
Václav Škorpil
12/12/2021, 8:47 PMFrancesc
12/12/2021, 8:48 PMFrancesc
12/12/2021, 8:49 PMVáclav Škorpil
12/12/2021, 8:53 PMfun getKeywordData(
keywordId: UUID,
): Flow<String> = flow {
val name = keywordRepo.getKeywordName() // suspend function
val secondArgument = differentRepo.getArgument() // suspend function
val thirdArgument = differentRepo.getThirdArgument() // suspend function
val dataFlow = keywordRepo.getKeywordData(name, secondArgument, thirdArgument) // function that returns flow
emitAll(dataFlow)
}
If you have something like this, then you would need to create a class to wrap them and return them in a flow right?Francesc
12/12/2021, 8:56 PMcombine
to collect them allFrancesc
12/12/2021, 8:58 PMcombine(
flow { emit(suspendOne()) },
flow { emit(suspendTwo()) },
) { one, two ->
MyData(one, two)
}.flatmapLatest { data ->
myFlow(data)
}
Francesc
12/12/2021, 9:01 PMsuspend fun aggregator(): MyData {
val one = getOne()
val two = getTwo()
return MyData(one, two)
}
and you could also use async
to make these 2 run in parallel
suspend fun aggregator(): MyData = coroutineScope {
val one = async { getOne() }
val two = async { getTwo() }
return MyData(one.await(), two.await())
}
Václav Škorpil
12/12/2021, 9:03 PMFrancesc
12/12/2021, 9:05 PMFrancesc
12/12/2021, 9:05 PMVáclav Škorpil
12/12/2021, 9:09 PM