LiveData Observer首次未触发Realmresults

时间:2019-03-14 11:12:48

标签: android mvvm kotlin realm android-livedata

我正在经历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,实时数据更新将被调用并更新我的列表。请让我知道如何解决此问题。

1 个答案:

答案 0 :(得分:1)

我们需要将现有数据通知观察者。当第一个观察者注册到historyViewModel.getList()时,您正在注册领域回调。在这一点上,我们需要触发更改,只是为了通知此观察者现有数据。

类似

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)
}
}