In my ViewModel, I’m fetching data from an API using repository.remote.getNews()
. I can see in the logs that the API is successfully called and returns data.
However, the data is not displayed in the _newsList
variable, which is of type LiveData<NetworkRequest<ResponseNews>>
, and its value is null.
API : News forex
logcat image :
ViewModel :
@HiltViewModel
class HomeViewModel @Inject constructor(private val repository: HomeRepository) : ViewModel() {
private var _newsList = MutableLiveData<NetworkRequest<ResponseNews>>()
val newsList: LiveData<NetworkRequest<ResponseNews>> = _newsList
init {
viewModelScope.launch {
getNews()
}
}
private fun getNews() = viewModelScope.launch {
_newsList.value = NetworkRequest.Loading()
val response = repository.remote.getNews()
_newsList.value = NetworkResponse(response).generateResponse()
Log.d("HomeFragment", "News list: $_newsList")
}
}
Question:
What could be causing the data to be successfully fetched from the API but displayed as null in _newsList
?
Additional Information:
-
I’m using Hilt for dependency injection.
-
I’m using Coroutines to manage asynchronous tasks.
-
I can see in the logs that
response
(the variable containing the API data) is not null.
Goal:
To find the reason why _newsList
is null and fix it to display the data correctly in LiveData.
Considerations:
-
Please let me know if you need any more information.
-
Any guidance or suggestions to solve this issue would be greatly appreciated.
Thank you!