将来自EventListener的数据保存在MutableLiveData中

时间:2019-01-27 14:18:08

标签: android google-cloud-firestore android-livedata android-viewmodel

我正在尝试从Firestore检索数据,并希望将其保留在共享视图模型中。基本上,我有一个主要活动和两个片段,它们需要从主要活动的共享视图模型中检索数据。我当前的方法是:

class SharedViewModel: ViewModel() {

private val firebaseUtils = FirebaseUtils()

fun getTempWords(localeLearn: String): LiveData<DocumentSnapshot> {
    val document = firebaseUtils.getTempWordsLocaleRef(localeLearn)

    return FirebaseDocumentLiveData(document)
}}

我想要的是只检索一次数据,并将其保存在MutableLiveData中,然后传递给fragmetns。

编辑: 我要做的是:

var tempWords : MutableLiveData<DocumentSnapshot> = MutableLiveData()
fun getTemp(localeLearn: String): LiveData<DocumentSnapshot> {

    if (tempWords.value == null) {
        val document = firebaseUtils.getTempWordsLocaleRef(localeLearn)
        tempWords = FirebaseDocumentLiveData(document)
    }
    return tempWords
}

但是,如果我杀死该片段并再次创建它,它将再次在FirebaseDocumentLiveData(document)类中调用EventListener。

编辑2: 我的片段

private lateinit var model: SharedViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    //
    model = activity?.run {
        ViewModelProviders.of(this).get(SharedViewModel::class.java)
    } ?: throw Exception("Invalid Activity")
}

//
 model.getTemp(mLocaleLearn!!).observe(this, Observer {...}

1 个答案:

答案 0 :(得分:0)

这是什么问题?看来您成功做到了。 您问如何从片段中访问数据?

在视图模型类中

private final MutableLiveData<Item> data = new MutableLiveData<Item>();

在您的片段中:

model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);