我在做一个应用程序,它得到的(伪)延迟时间值是通过出请求的一些网址和录像多长时间,将采取。
第一,我使用的改型,会返回一个响应从一个网络服务器。 这种反应包括:主机名(例如Ebay联合王国),该网址的主机(例如 www.ebay.co.uk),和一个镜像网址。 我地图的这种反应到我的数据类如下:
data class(
val name: String,
var url: String,
val icon: String,
var averagePing: Long = -1
)
网址是一个var财产之前作出的呼吁得到延迟时间值,我需要增加https://为了使该请求。
我做的这一切就像这样:
fun getHostsLiveData() {
viewModelScope.launch(Dispatchers.IO) {
val hostList = repo.getHosts()
for (host in hostList) {
host.url = "https://" + host.url
host.averagePing = -1
}
hostListLiveData.postValue(hostList)//updated the recyclerview with initial values
//with default (-1) value of averagePing
for (host in hostList) {
async { pingHostAndUpdate(host.url, hostList) }
}
}
}
第一次循环的准备我的数据。 线后对环数据提交给回收器,以显示主机名称,网址和标直接(这一切工作,即我们工作的观察员对其中),而我在等待等待时间值。
第二循环的呼吁函数计算的延迟时间值为每个主和updateHostList()功能就更新其中.
这是如何的功能看:
suspend fun pingHostAndUpdate(url: String, hostList: MutableList<Host>) {
try {
val before = Calendar.getInstance().timeInMillis
val connection = URL(url).openConnection() as HttpURLConnection //Need error handling
connection.connectTimeout = 5*1000
connection.connect()
val after = Calendar.getInstance().timeInMillis
connection.disconnect()
val diff = after - before
updateHostList(url, diff, hostList)
} catch (e: MalformedURLException) {
Log.e("MalformedURLExceptionTAG", "MalformedURLException")
} catch (e: IOException) {
Log.e("IOExceptionTAG", "IOException")
}
}
fun updateHostList(url: String, pingResult: Long, hostList: MutableList<Host>) {
//All this on mainThread
var foundHost: Host? = null
var index = 0
for (host in hostListLiveData.value!!) {
if (host.url == url) {
foundHost = host
break
}
index++
}
if (foundHost != null) {
viewModelScope.launch(Dispatchers.Main) {
val host = Host(foundHost.name, foundHost.url, foundHost.icon, pingResult)
Log.d("TAAAG", "$host")
hostList[index] = host
hostListLiveData.value = hostList
}
}
}
所有这一切都发生在模型. 目前我要更新我的名单提交整个列表再次当我改变的一个酒店中的一个元素的清单,这似乎太可怕了我。
我的问题是:如何更新,只有一个酒店的东道并刷新UI自动?
在此先感谢
编辑:我的观察者看起来像这样:
viewModel.hostListLiveData.observe(this, Observer { adapter.updateData(it) })
和updateData()看起来是这样的:
fun updateData(freshHostList: List<Host>) {
hostList.clear()
hostList.addAll(freshHostList)
notifyDataSetChanged()
}
@ArpitShukla,你建议我有2个更新的功能吗? 一个表示的初步清单和另一个更新项目的清单? 或者我只是把这两个notifyDataSetChanged()和notifyItemChanged()在updateData()?
Edit2:改变我的功能的电话,使它异步.