0

I'm trying to load data from Firebase into a RecyclerView, however nothing shows up until I reload my fragment.

This is my onCreate method in SubjectsFragment:

viewModel.subjectsListLiveData.observe(
            this,
            Observer { list ->
                subjectsAdapter.swapSubjectsList(list)
                if (subject_list != null && list.size != 0) Animations.runLayoutAnimation(
                    subject_list
                )
            })
viewModel.lessonsListLiveData.observe(
            this,
            Observer { list ->
                subjectsAdapter.swapLessonsList(list)
                if (subject_list != null && list.size != 0) Animations.runLayoutAnimation(
                    subject_list
                )
            })

This is SubjectsFragmentViewModel:

    private val subjectsList = MutableLiveData<ArrayList<Subject>>()
    val subjectsListLiveData: LiveData<ArrayList<Subject>>
        get() = subjectsList

    private val lessonsList = MutableLiveData<ArrayList<Lesson>>()
    val lessonsListLiveData: LiveData<ArrayList<Lesson>>
        get() = lessonsList

    init {
        loadSubjects()
        loadLessonsForSubjects()
    }

    fun loadSubjects() {
        GlobalScope.launch {
            val subjects = FirebaseUtils.loadAllSubjects()
            subjectsList.postValue(subjects)
        }
    }

    fun loadLessonsForSubjects() {
        GlobalScope.launch {
            val lessons = FirebaseUtils.loadAllLessons()
            lessonsList.postValue(lessons)
        }
    }

I don't have any problems once I reload the fragment. Could someone please explain to me what I'm doing wrong?

milancodes
  • 173
  • 1
  • 7

1 Answers1

1

Try using setValue directly. But you may be right, using postValue from a background thread is the way it should be done.

Also, attach your observers in onActivityCreated()

Espera Awo
  • 40
  • 5
  • Thanks! Attaching my observers in onActivityCreated solved the problem for me! – milancodes Mar 16 '20 at 14:33
  • If anyone's facing the same issue, another problem of mine was that I used Firebase as functions that return values - see more here: https://stackoverflow.com/a/42811962/9409337 – milancodes Mar 16 '20 at 15:45
  • Yes it's not a good design pattern. Those requests should be in your repository then sent to your viewModel. Your viewModel observe your repo – Espera Awo Mar 16 '20 at 16:11