【发布时间】:2020-08-04 07:44:06
【问题描述】:
我的 Android 应用程序基于 TCP 协议。
当我初始化与服务器的连接时,我正在发送一条特殊的字节消息,并且必须等待服务器的响应。
在所有存储库示例中,我看到存储库始终具有调用信息源并返回(来自 Android 开发人员)的方法:
class UserRepository {
private val webservice: Webservice = TODO()
// ...
fun getUser(userId: String): LiveData<User> {
// This isn't an optimal implementation. We'll fix it later.
val data = MutableLiveData<User>()
webservice.getUser(userId).enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
data.value = response.body()
}
// Error case is left out for brevity.
override fun onFailure(call: Call<User>, t: Throwable) {
TODO()
}
})
return data
}
}
getUser 函数返回一个 LiveData 的数据。 在我的应用程序中,方法 Login 什么都不返回,因为我等待服务器发送带有特殊代码的字节,以知道它正在响应我的登录请求。
有没有办法用类似的 TCP 协议来实现这种模式?
谢谢
【问题讨论】:
-
The function getUser return a data of LiveData。看起来是这样的。但它会返回用户吗? -
I'm sending a special bytes message and have to wait the response of the server.是的,但是当你在线程中这样做时,你可以同时做所有其他类型的事情。一旦收到响应,线程就可以调用runOnUiThread。所以这就是你所需要的。 -
目前,当我在线程中收到响应时,我使用接口在我的 UI 线程中获取数据并更新 UI。但我没有使用 LiveData,而是使用存储库模式的目标
标签: android repository-pattern android-livedata android-architecture-components