【发布时间】:2018-11-22 08:39:58
【问题描述】:
我正在基于 Android Clean Architecture Kotlin 版本 (https://github.com/android10/Android-CleanArchitecture-Kotlin) 构建应用。
使用这种架构,每次你想调用一个用例时,都会启动一个 Kotlin 协程,并将结果发布到主线程中。这是通过以下代码实现的:
abstract class UseCase<out Type, in Params> where Type : Any {
abstract suspend fun run(params: Params): Either<Failure, Type>
fun execute(onResult: (Either<Failure, Type>) -> Unit, params: Params) {
val job = async(CommonPool) { run(params) }
launch(UI) { onResult.invoke(job.await()) }
}
在他的示例架构中,Android10 先生使用 Retrofit 在 kotlin couroutine 内进行同步 api 调用。例如:
override fun movies(): Either<Failure, List<Movie>> {
return when (networkHandler.isConnected) {
true -> request(service.movies(), { it.map { it.toMovie() } }, emptyList())
false, null -> Left(NetworkConnection())
}
}
private fun <T, R> request(call: Call<T>, transform: (T) -> R, default: T): Either<Failure, R> {
return try {
val response = call.execute()
when (response.isSuccessful) {
true -> Right(transform((response.body() ?: default)))
false -> Left(ServerError())
}
} catch (exception: Throwable) {
Left(ServerError())
}
}
'Either' 表示不相交的类型,意味着结果要么是失败,要么是你想要的 T 类型的对象。
他的 service.movies() 方法是这样实现的(使用改造)
@GET(MOVIES) fun movies(): Call<List<MovieEntity>>
现在这是我的问题。我正在用 Google Cloud Firestore 替换改造。我知道目前,Firebase/Firestore 是一个全异步库。我想知道是否有人知道对 Firebase 进行同步 API 调用的更优雅的方法。
我实现了自己的 Call 版本:
interface Call<T: Any> {
fun execute(): Response<T>
data class Response<T>(var isSuccessful: Boolean, var body: T?, var failure: Failure?)
}
我的API调用在这里实现
override fun movieList(): Call<List<MovieEntity>> = object : Call<List<MovieEntity>> {
override fun execute(): Call.Response<List<MovieEntity>> {
return movieListResponse()
}
}
private fun movieListResponse(): Call.Response<List<MovieEntity>> {
var response: Call.Response<List<MovieEntity>>? = null
FirebaseFirestore.getInstance().collection(DataConfig.databasePath + MOVIES_PATH).get().addOnCompleteListener { task ->
response = when {
!task.isSuccessful -> Call.Response(false, null, Failure.ServerError())
task.result.isEmpty -> Call.Response(false, null, MovieFailure.ListNotAvailable())
else -> Call.Response(true, task.result.mapTo(ArrayList()) { MovieEntity.fromSnapshot(it) }, null)
}
}
while (response == null)
Thread.sleep(50)
return response as Call.Response<List<MovieEntity>>
}
当然,最后的while循环让我很困扰。有没有其他更优雅的方法来等待响应被分配,然后再从movieListResponse方法返回? p>
我尝试在从 Firebase get() 方法返回的 Task 上调用 await(),但 movieListResponse 方法无论如何都会立即返回。感谢您的帮助!
【问题讨论】:
-
所有用于移动和网络客户端的 Firebase API 都是异步的。协程实际上也是异步的,但编译器只是通过内部重组代码使它们看起来是同步的。
标签: android firebase kotlin google-cloud-firestore coroutine