Reputation: 41
When I want to set live-data to mutable live data I call live data.getvalue() but it returns null
private const val TAG = "MainViewModel"
@HiltViewModel class MainViewModel @Inject constructor(private val repository: VaultRepository) : ViewModel() { private var dashMutableData = MutableLiveData<List>() var dashLiveData: LiveData<List> = dashMutableData
init {
Log.d(TAG, " Init Executed ")
viewModelScope.launch(Dispatchers.Default) {
var liveData: LiveData<List<CategoriesModel>> = repository.getDashBoardData()
Log.d(TAG, "${liveData.value}")
dashMutableData.postValue(liveData.value)
}
}
}
Upvotes: 0
Views: 3839
Reputation: 1316
Why return LiveData
from your repository if you are not going to observe it? You could just return List<CategoriesModel>
from your repository.
LiveData
does not have a value unless it has an observer. If you add an observer, it will get a value once the observer has triggered once.
You shouldn't do this, but just to prove the point, if you add an observer before accessing the value it should work:
init {
Log.d(TAG, " Init Executed ")
viewModelScope.launch(Dispatchers.Default) {
var liveData: LiveData<List<CategoriesModel>> = repository.getDashBoardData()
livedata.observeForever(object: Observer<T> {
override fun onChanged(value: T) {
removeObserver(this)
}
})
delay(100) //not sure this is needed, just making sure the observer triggered once.
dashMutableData.postValue(liveData.value)
Log.d(TAG, "${liveData.value}")
}
}
Upvotes: 0