LiveData Observer 没有被 kotlin 协程调用

LiveData Observer not getting called with kotlin coroutine

我从远程服务器得到一个文件列表,然后我需要下载每个文件,下载完成后,我应该通知 UI 显示,但 livedata observer 没有被调用。 我在下面写了一个演示,

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

将您的 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 个协程并在其中迭代您的文件列表。

liveData.postValue

如果您需要从后台线程设置一个值,您可以使用 postValue(Object)

将任务发布到主线程以设置给定值。

如果在主线程执行发布任务之前多次调用此方法,则只会调度最后一个值。

所以将 postValue 更改为 setValue 后一切正常