android - 如何在 Kotlin 中为 RxJava 函数创建一个安全的调用包装器?
问题描述
下面粘贴的是来自 Google 的Plaid应用程序的一段代码,它封装了挂起函数并安全地执行网络操作。需要进行哪些更改才能使其与 RxJava 函数而不是 Coroutines 一起使用并等待网络结果,感谢任何帮助。
/**
* Wrap a suspending API [call] in try/catch. In case an exception is thrown, a [Result.Error] is
* created based on the [errorMessage].
*/
suspend fun <T : Any> safeApiCall(call: suspend () -> Result<T>, errorMessage: String): Result<T> {
return try {
call()
} catch (e: Exception) {
// An exception was thrown when calling the API so we're converting this to an IOException
Result.Error(IOException(errorMessage, e))
}
}
ProductHuntRemoteDataSource.kt中的使用示例:
class ProductHuntRemoteDataSource @Inject constructor(private val service: ProductHuntService) {
/**
* Load Product Hunt data for a specific page.
*/
suspend fun loadData(page: Int) = safeApiCall(
call = { requestData(page) },
errorMessage = "Error loading ProductHunt data"
)
private suspend fun requestData(page: Int): Result<GetPostsResponse> {
val response = service.getPostsAsync(page)
if (response.isSuccessful) {
val body = response.body()
if (body != null) {
return Result.Success(body)
}
}
return Result.Error(IOException("Error loading ProductHunt data " +
"${response.code()} ${response.message()}"))
}
}
解决方案
awaitFirst()
你可以通过使用or await()
(对于 Single )扩展函数将你的 observable 转换为挂起函数来轻松地使用 RxJava 。您需要使用RxJava扩展。
编辑:
你可以在你的 observables 上写一个扩展函数来做一些类似但不完全相同的事情。
这是一个可能的解决方案
fun <T> Observable<Result<T>>.safeCall(errorMessage: String, block: (Result<T>) -> Unit): Disposable =
subscribe({ response: Result<T> ->
if (response.isSuccess && response.body != null) {
block(Result.Success(response.body))
} else {
block(Result.Error(IOException(errorMessage)))
}
}, { throwable ->
block(Result.Error(IOException(errorMessage, throwable)))
})
你会在这样的可观察对象上调用它
val disposable = myObservable.safeCall("Error message") { result ->
// TODO: handle result
}
推荐阅读
- flutter - 为什么 FutureBuilder 不返回从 Sqlite 数据库查询的数据?
- javascript - 对象类型
- linkedin - 链接帖子中的自定义图像无法通过用于 LinkedIn 个人资料的 API
- c# - C# Linq JSON 嵌套数组的奇怪行为
- android - 无法解析符号 PreferenceFragmentCompat
- excel - 超链接点击运行功能两次并给出补丁错误
- javascript - 启动 Selenium IE11 WebDriver 或执行 JS 时 Python 操作卡住
- android - 收藏功能如何?
- haskell - Haskell Cabal+Nix:为项目中的所有依赖项生成本地文档
- r - 计算R中data.table中每组计数变量的比例