Hey guys when I code like this, it makes my app cr...
# android
t
Hey guys when I code like this, it makes my app crashes because of stackoverflow error at LazyImpl kotlin. Is it illegal to access the variable catFacts like this?
class CatFactsViewModel : ViewModel() {
private val catFacts: MutableLiveData<List<String>> by lazy {
MutableLiveData<List<String>>().also {
loadCatFacts()
}
}
fun getCatFacts(): LiveData<List<String>> {
return catFacts
}
private fun loadCatFacts() {
// Do an asynchronous operation to fetch cat facts.
catFacts.value = listOf("fact 1", "fact 2")
}
}
h
But why are you lazy initialising it?
ViewModel private val _catFacts = MutableLiveData<List<String>>() val catFacts : LiveData<List<String>> = _catFacts fun loadCatFacts() { // Network Call _catFacts.value = listof() } Activity/Fragment val list = viewmodel.catFacts.value Does this work for you?
m
private val _catFacts = MutableLiveData<List<String>>() val catFacts : LiveData<List<String>> = _catFacts fun loadCatFacts() { // Network Call _catFacts.value = listof() } From Activity or Fragment you need to observe live data. So whenever you call loadCatFacts() method it will update livedata and you will get notify in onChanged() method with updated data. So you can set it wherever you want.
h
Right, but no need of lazy initialisation which was causing the crash
t
Yeah I had to not use lazy load
it stops crashing