我只对此进行了简单的测试来验证它,但看起来你可以监听查询,并根据外部Flow的上下文在新启动的协程中发出它传播的任何/所有数据——函数中的其他工作将继续进行,不受阻碍。一旦完成了其他工作,就可以取消监听查询的协程。例如:
inline fun <ResultType, RequestType> networkBoundResource(
crossinline query: () -> Flow<ResultType>,
crossinline fetch: suspend () -> RequestType,
crossinline saveFetchResult: suspend (RequestType) -> Unit,
crossinline onFetchFailed: (Throwable) -> Unit = { },
crossinline shouldFetch: (ResultType) -> Boolean = { true }
): Flow<Resource<ResultType>> = flow {
emit(Resource.Loading())
val data = query().first()
val flow = if (shouldFetch(data)) {
val flowContext = currentCoroutineContext()
val loading: Job = coroutineScope {
launch(flowContext) {
query().map { Resource.Loading(it) }
.collect { withContext(flowContext) { emit(it) } }
}
}
try {
val request = fetch()
loading.cancel()
saveFetchResult(request)
query().map { Resource.Success(it) }
} catch (throwable: Throwable) {
loading.cancel()
onFetchFailed(throwable)
query().map { Resource.Error(throwable, it) }
}
} else {
query().map { Resource.Success(it) }
}
emitAll(flow)
}
如果成功了,请告诉我!