@@ -22,13 +22,19 @@ import androidx.lifecycle.MutableLiveData
22
22
import androidx.lifecycle.ViewModel
23
23
import com.google.firebase.firestore.FirebaseFirestore
24
24
import com.google.firebase.firestore.Query
25
+ import com.google.firebase.firestore.QuerySnapshot
25
26
import com.hossainkhan.android.demo.data.ResourceInfo
26
27
import timber.log.Timber
28
+ import java.lang.Exception
27
29
import javax.inject.Inject
28
30
29
31
class LearningResourceViewModel @Inject constructor(
30
32
firestore : FirebaseFirestore
31
33
) : ViewModel() {
34
+ companion object {
35
+ private const val RESOURCE_COLLECTION = " external-resources"
36
+ }
37
+
32
38
val isLoading = ObservableField (true )
33
39
34
40
private val _data = MutableLiveData <List <ResourceInfo >>()
@@ -38,22 +44,25 @@ class LearningResourceViewModel @Inject constructor(
38
44
39
45
init {
40
46
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 )
43
49
.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 )
58
67
}
59
68
}
0 commit comments