简体   繁体   English

首次更新后 Android LiveData Observer 未激活

[英]Android LiveData Observer not active after first update

I'm trying out a basic implementation of Architecture Component's Live Data with Kotlin like this:我正在尝试使用 Kotlin 对架构组件的实时数据进行基本实现,如下所示:

class MarketFragment : LifecycleFragment(){
......
 override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel=ViewModelProviders.of(this).get(MarketViewModel::class.java)
        viewModel.book?.observe(this, Observer { book-> //updateUI })
....

My ViewModel class is created like this:我的 ViewModel 类是这样创建的:

class MarketViewModel : ViewModel()
{
    var book: MutableLiveData<Book>? =MutableLiveData()
    var repository: Repository?= Repository()

    init {
        update("parameter")
    }

    fun update(s: String)
    {
         book=repository?.getBook(s)

    }

}

And My Repository:和我的存储库:

fun getBook(bookSymbol:String):MutableLiveData<Book>
{
    val book=MutableLiveData<Book>()
    ......

            call . enqueue (object : Callback<Book> {
        override fun onResponse(call: Call<Book>?, response: Response<Book>?) {

            book.value=response?.body()

        }
     .....
    })
            return book
}

} }

And all of this works great and UI is updated as it should but only for the first time.所有这些都非常有效,并且 UI 已按应有的方式更新,但只是第一次更新。 If i try to make manual calls to update the viewModel from a UI action, the retrofit call still works as expected but the new data is not sent to the Observer in the Fragment:如果我尝试手动调用从 UI 操作更新 viewModel,改造调用仍然按预期工作,但新数据不会发送到 Fragment 中的观察者:

//this doesn't work:
viewModel.update("string")
//This returns false:
viewModel.book.hasActiveObservers()

Is it the expected behaviour for an Observer to become inactive after the first trigger?观察者在第一次触发后变为非活动状态是预期行为吗?

You are creating a new MutableLiveData instance each time you are calling getBooks每次调用getBooks时都会创建一个新的 MutableLiveData 实例

Hence your observer is not observing the right LiveData anymore.因此,您的观察者不再观察正确的LiveData

To solve this为了解决这个

  1. Your ViewModel should keep only one (immutable) LiveData instance您的 ViewModel 应该只保留一个(不可变的)LiveData 实例
  2. That immutable LiveData instance could either be:那个不可变的 LiveData 实例可以是:

    • A MediatorLiveData, which source is the repository's LiveData MediatorLiveData,其来源是存储库的 LiveData
    • A transformation of the repository's LiveData存储库 LiveData 的转换

That implies the repository method getBooks is only called once on initialization of the ViewModel, and that either refreshes itself OR you have to call another method on the repository to trigger a refresh.这意味着存储库方法getBooks仅在 ViewModel 初始化时调用一次,并且要么刷新自身,要么您必须调用存储库上的另一个方法来触发刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM