我目前有一个逻辑如下:
interface anotherRepository {
fun getThings(): Flow<List<String>>
}
interface repository {
suspend fun getSomeThings(): AsyncResult<SomeThings>
}
when (val result = repository.getSomeThings()) {
is AsyncResult.Success -> {
anotherRepository.getThings().collectLatest {
// update the state
}
else -> { }
}
}
我遇到的问题是,如果repository.getSomeThings
以前被触发过多次,那么anotherRepository.getThings
将被触发,用于repository.getSomeThings
中所有预加载值的数量。我想知道使用这些存储库的正确方法是什么,一个是挂起函数,另一个是Flow。在Rx中组合Latest{}的等效行为。
谢谢。
有几种方法可以解决您的问题。一种方法就是打电话collectLatest
块中的repository.getSomeThings()
和缓存最后结果:
var lastResult: AsyncResult<SomeThings>? = null
anotherRepository.getThings().collectLatest {
if (lastResult == null) {
lastResult = repository.getSomeThings()
}
// use lastResult and List<String>
}
另一种方法是创建一个Flow
,它将调用repository.getSomeThings()
函数和combine
两个流:
combine(
anotherRepository.getThings(),
flow {emit(repository.getSomeThings())}
) { result1: List<String>, result2: AsyncResult<SomeThings> ->
...
}