【问题标题】:LiveData Observer not getting called with kotlin coroutineLiveData Observer 没有被 kotlin 协程调用
【发布时间】:2020-04-17 04:45:36
【问题描述】:

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

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 被调用

【问题讨论】:

    标签: android android-livedata


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      liveData.postValue

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        相关资源
        最近更新 更多