PostValue并未更新MVVM中的观察者

时间:2019-08-08 02:30:14

标签: android kotlin mvvm kotlin-coroutines

我有一个活动,每次打开它都会执行rest API,并且我为此项目使用MVVM模式。但是使用此代码段代码,每次打开活动时我都无法更新。因此,我在每一行中调试了所有参数,它们都很好地解决了apiService.readNewsAsync(param1,param2)执行时可能出现的问题,我的postValue没有更新我的resulRead参数。这里没有崩溃,但是我得到了未从结果(postValue)更新的结果。有人可以向我解释为什么会这样吗? 这里的活动看起来像

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DataBindingUtil.setContentView<ActivityReadBinding>(this,
            R.layout.activity_read).apply {
            this.viewModel = readViewModel
            this.lifecycleOwner = this@ReadActivity
        }
        readViewModel.observerRead.observe(this, Observer {
            val sukses = it.isSuccess
            when{
                sukses -> {
                    val data = it.data as Read
                    val article = data.article
                    //Log.d("-->", "${article.toString()}")
                }
                else -> {
                    toast("ada error ${it.msg}")
                    Timber.d("ERROR : ${it.msg}")
                }
            }

        })
                readViewModel.getReadNews()
    }

视图模型

var observerRead = MutableLiveData<AppResponse>()

 init {
        observerRead = readRepository.observerReadNews()
    }


fun getReadNews() {

        // kanal and guid i fetch from intent and these value are valid

        loadingVisibility = View.VISIBLE
        val ok = readRepository.getReadNews(kanal!!, guid!!)
        if(ok){
            loadingVisibility = View.GONE
        }
    }

库存

class ReadRepositoryImpl private constructor(private val newsdataDao: NewsdataDao) : ReadRepository{
    override fun observerReadNews(): MutableLiveData<AppResponse> {
        return newsdataDao.resultRead
    }

    override fun getReadNews(channel: String, guid: Int) = newsdataDao.readNews(channel, guid)

    companion object{
        @Volatile private var instance: ReadRepositoryImpl? = null

        fun getInstance(newsdataDao: NewsdataDao) = instance ?: synchronized(this){
            instance ?: ReadRepositoryImpl(newsdataDao).also {
                instance = it
            }
        }
    }
}

模型/数据源

class NewsdataDao {

    private val apiService = ApiClient.getClient().create(ApiService::class.java)
    var resultRead = MutableLiveData<AppResponse>()

    fun readNews(channel: String, guid: Int): Boolean{
        GlobalScope.launch {
            val response = apiService.readNewsAsync(Constants.API_TOKEN, channel, guid.toString()).await()
            when{
                response.isSuccessful -> {
                    val res = response.body()
                    val appRes = AppResponse(true, "ok", res!!)
                    resultRead.postValue(appRes)
                }
                else -> {
                    val appRes = AppResponse(false, "Error: ${response.message()}", null)
                    resultRead.postValue(appRes)
                }
            }
        }
        return true
    }
}

1 个答案:

答案 0 :(得分:0)

也许这个活动没有停止。

检查一下: enter image description here

当您在onCreate()中调用readViewModel.getReadNews()时,您的活动将被创建一次,只有在onStop被调用时,活动才会被再次创建。