@@ -22,13 +22,19 @@ import androidx.lifecycle.MutableLiveData
2222import androidx.lifecycle.ViewModel
2323import com.google.firebase.firestore.FirebaseFirestore
2424import com.google.firebase.firestore.Query
25+ import com.google.firebase.firestore.QuerySnapshot
2526import com.hossainkhan.android.demo.data.ResourceInfo
2627import timber.log.Timber
28+ import java.lang.Exception
2729import javax.inject.Inject
2830
2931class 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