我从远程服务器获取文件列表,然后需要下载每个文件,下载完成后,我应该通知UI进行显示,但不会调用livedata观察器。 我在下面写一个演示,
class MainActivity : AppCompatActivity() {
val liveData = MutableLiveData<Test>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
liveData.observe(this, Observer {
Log.d("Test","receive ${it.pos}")
})
}
override fun onResume() {
super.onResume()
// example this is a file list
for (i in 0..15){
lifecycleScope.launch {
withContext(Dispatchers.IO){
delay(100)// download file or check file is exits
Log.d("Test","send $i")
liveData.postValue(Test(i))
}
}
}
}
}
获取日志
2020-04-17 12:35:21.847 15449-15490 D/Test: send 2
2020-04-17 12:35:21.848 15449-15491 D/Test: send 3
2020-04-17 12:35:21.849 15449-15495 D/Test: send 0
2020-04-17 12:35:21.853 15449-15491 D/Test: send 5
2020-04-17 12:35:21.873 15449-15490 D/Test: send 1
2020-04-17 12:35:21.873 15449-15496 D/Test: send 4
2020-04-17 12:35:21.876 15449-15491 D/Test: send 6
2020-04-17 12:35:21.883 15449-15449 D/Test: receive 6
2020-04-17 12:35:21.898 15449-15490 D/Test: send 10
2020-04-17 12:35:21.899 15449-15492 D/Test: send 9
2020-04-17 12:35:21.899 15449-15497 D/Test: send 7
2020-04-17 12:35:21.900 15449-15499 D/Test: send 11
2020-04-17 12:35:21.900 15449-15499 D/Test: send 13
2020-04-17 12:35:21.901 15449-15499 D/Test: send 14
2020-04-17 12:35:21.901 15449-15490 D/Test: send 12
2020-04-17 12:35:21.902 15449-15494 D/Test: send 8
2020-04-17 12:35:21.903 15449-15494 D/Test: send 15
2020-04-17 12:35:21.964 15449-15449 D/Test: receive 15
为什么只有两次观察者onChanged被调用
答案 0 :(得分:0)
将您的onResume()
更改为此:
override fun onResume() {
super.onResume()
lifecycleScope.launch {
withContext(Dispatchers.IO) {
for (i in 0..15) {
delay(100)// download file or check file is exits
Log.d("Test", "send $i")
liveData.postValue(Test(i))
}
}
}
}
您启动1个协程,并在其中迭代文件列表。
答案 1 :(得分:0)
liveData.postValue
如果需要从后台线程设置值,则可以使用postValue(Object)
将任务发布到主线程以设置给定值。
如果在主线程执行发布的任务之前多次调用此方法,则只会分派最后一个值。
因此将postValue更改为setValue后一切正常