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?

1
  • Did my answer help you? Commented Mar 16, 2020 at 13:01

1 Answer 1

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()

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Attaching my observers in onActivityCreated solved the problem for me!
If anyone's facing the same issue, another problem of mine was that I used Firebase as functions that return values - see more here: stackoverflow.com/a/42811962/9409337
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.