Skip to content
This repository was archived by the owner on Aug 22, 2024. It is now read-only.

Commit 9bccdc0

Browse files

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

app/src/main/java/com/hossainkhan/android/demo/ui/resource/LearningResourceViewModel.kt

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,19 @@ import androidx.lifecycle.MutableLiveData
2222
import androidx.lifecycle.ViewModel
2323
import com.google.firebase.firestore.FirebaseFirestore
2424
import com.google.firebase.firestore.Query
25+
import com.google.firebase.firestore.QuerySnapshot
2526
import com.hossainkhan.android.demo.data.ResourceInfo
2627
import timber.log.Timber
28+
import java.lang.Exception
2729
import javax.inject.Inject
2830

2931
class LearningResourceViewModel @Inject constructor(
3032
firestore: FirebaseFirestore
3133
) : ViewModel() {
34+
companion object {
35+
private const val RESOURCE_COLLECTION = "external-resources"
36+
}
37+
3238
val isLoading = ObservableField(true)
3339

3440
private val _data = MutableLiveData<List<ResourceInfo>>()
@@ -38,22 +44,25 @@ class LearningResourceViewModel @Inject constructor(
3844

3945
init {
4046
Timber.i("Loading data from firestore: %s", firestore)
41-
firestore.collection("external-resources")
42-
.orderBy("publish_date", Query.Direction.DESCENDING)
47+
firestore.collection(RESOURCE_COLLECTION)
48+
.orderBy(ResourceInfo::publish_date.name, Query.Direction.DESCENDING)
4349
.get()
44-
.addOnSuccessListener { result ->
45-
for (document in result) {
46-
val x = document.toObject(ResourceInfo::class.java)
47-
Timber.i("Resource: $x")
48-
resourceData.add(x)
49-
}
50-
isLoading.set(false)
51-
_data.value = resourceData
52-
53-
}
54-
.addOnFailureListener { exception ->
55-
isLoading.set(false)
56-
Timber.w(exception, "Error getting documents.")
57-
}
50+
.addOnSuccessListener(this::updateResources)
51+
.addOnFailureListener(this::onLoadFailed)
52+
}
53+
54+
private fun updateResources(result: QuerySnapshot) {
55+
for (document in result) {
56+
val x = document.toObject(ResourceInfo::class.java)
57+
Timber.i("Resource: $x")
58+
resourceData.add(x)
59+
}
60+
isLoading.set(false)
61+
_data.value = resourceData
62+
}
63+
64+
private fun onLoadFailed(exception: Exception) {
65+
Timber.w(exception, "Error getting documents.")
66+
isLoading.set(false)
5867
}
5968
}

0 commit comments

Comments
 (0)