I want to show a movie list from Firebase realtime database, but I'm not getting the list from the ViewModel.
When I update the apiResource.data in the Repository, it is not updating the mutableList on the screen.
Screen:
val movies = viewModel.data.value.data?.toMutableList()
if (viewModel.data.value.loading == true) {
CircularProgressIndicator()
} else {
movies?.forEach {
Log.d("Movies", it.name) // I'm not getting the movie list on the screen
}
}
ViewModel:
val data: MutableState<ApiResource<List<Movie>, Boolean, Exception>> = mutableStateOf(
ApiResource(null, true, Exception(""))
)
private fun getMovies() {
viewModelScope.launch {
data.value.loading = true
data.value = repository.getAllMovies()
if (data.value.data.toString() != "[]") {
data.value.loading = false
}
}
}
Repository:
class Repository {
private val apiResource = ApiResource<List<Movie>,Boolean, Exception>()
suspend fun getAllMovies(): ApiResource<List<Movie>, Boolean, java.lang.Exception> {
try {
apiResource.loading = true
var movies: List<Movie>
Firebase.database.reference.child("movies").addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
movies = dataSnapshot.children.map { snapshot ->
snapshot.getValue(Movie::class.java)!!
}
apiResource.data = movies // set data in apiResource
if (apiResource.data.toString() != "[]") {
apiResource.loading = false
}
}
override fun onCancelled(error: DatabaseError) {}
})
} catch (exception: java.lang.Exception) {
apiResource.e = exception
}
return apiResource
}
}