LiveData Observer实时结果没有被触发第一次

问题描述 投票:2回答:1

我正在通过Guide to app architecture尝试在我的一个应用程序中实现MVVM和LiveData。我正在使用领域,我正在使用this创建一个RealmLiveData,如下所示

class RealmLiveData<T : RealmModel>(private val results: RealmResults<T>) : MutableLiveData<RealmResults<T>>() {
private val listener = RealmChangeListener<RealmResults<T>> { results -> value = results }
override fun onActive() {
    results.addChangeListener(listener)
}

override fun onInactive() {
    results.removeChangeListener(listener)
}
}

这是我如何将列表更新为recyclerview

var mList:ArrayList<Notes> = ArrayList()

lateinit var historyViewModel: HistoryViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val view = inflater.inflate(R.layout.fragment_history, container, false)
    mRCview = view.findViewById(R.id.list)
    historyViewModel = ViewModelProviders.of(activity!!).get(HistoryViewModel::class.java)

    // this is how I observe
    historyViewModel.getList().observe(this, Observer{
        (mRCview.adapter as MyHistoryRecyclerViewAdapter).setData(it)
    })

    with(mRCview) {
        setHasFixedSize(true)
        layoutManager = LinearLayoutManager(mContext)
        mList = ArrayList()
        adapter = MyHistoryRecyclerViewAdapter(
            mContext as OnListFragmentInteractionListener
        )
    }
    return view
}

这就是我在我的存储库类中获取数据的方法

class HistoryRepository {

fun getHistory(): RealmLiveData<Notes> {
    val realmInstance = Realm.getDefaultInstance()
    val realmResults = realmInstance
        .where(Notes::class.java)
        .findAll()
        .sort("lastUpdatedTimeStamp", Sort.DESCENDING)
    return realmResults.asLiveData()
}

fun <T:RealmModel> RealmResults<T>.asLiveData() = RealmLiveData(this)
}

编辑

这是ViewModel

class HistoryViewModel: ViewModel() {

val repository = HistoryRepository()

fun getList(): RealmLiveData<Notes> {
    return repository.getHistory()
}
}

问题是观察者第一次没有被触发。如果我更新realmresult,则会调用实时数据更新并更新我的列表。请让我知道如何解决这个问题。

android mvvm kotlin realm android-livedata
1个回答
1
投票

我们需要通知Observer现有数据。当第一个Observer注册到historyViewModel.getList()时,您正在注册域回调。此时,我们需要触发更改,以便通知此Observer现有数据。

就像是

class RealmLiveData<T : RealmModel>(private val results: RealmResults<T>) : MutableLiveData<RealmResults<T>>() {
private val listener = RealmChangeListener<RealmResults<T>> { results -> value = results }
override fun onActive() {
    results.addChangeListener(listener)
    listener.onChange(results) // notify the added Observer of the existing data.
}

override fun onInactive() {
    results.removeChangeListener(listener)
}
}
© www.soinside.com 2019 - 2024. All rights reserved.