你可以用它
协同程序
像这样:
转弯
回拨
可悬函数
suspendCancellableCoroutine {...}
阻止:
suspend fun <T> request(requestBuilder: RequestBuilder): T = suspendCancellableCoroutine { cont ->
Server.asyncRequest(requestBuilder) { resource: T, error: ServiceError? ->
if(error != null)
cont.resumeWithException(error) // Makes the Flow throw an exception
else
cont.resume(resource) // Makes the Flow emit a correct result
}
}
创建
流量
使
:
val resourceOneFlow = flow {
emit(request<String>(RequestBuilder(endpoints.second, ids, params)))
}
创建
使
:
val resourceTwoFlow = flow {
emit(request<String>(RequestBuilder(endpoints.third, ids, params)))
}
联合收割机
二者都
流量
和
zip
val requestsResultFlow = resourceOneFlow.zip(resourceTwoFlow) { resourceOne, resourceTwo ->
// Build whatever you need with resourceOne and resourceTwo here and let it flow
"$resourceOne $resourceTwo".length // Here I concatenate both strings and return its length
}
流量
和
collect
运算符并使用其
结果
requestsResultFlow.collect { length ->
// Consume the result here
println("$length") // Here I print the number received
}
你有
here
.