0

I have a problem with MediatorLiveData. I want to get data from database, in class which is not ViewModel. I would like to point that methods which downloads data works in ViewModel, but when I want to invoke it in other class it doesn't work. This is a code:

class MyReceiver: BroadcastReceiver() {

@Inject
lateinit var jobsRepository: jobsRepository


private val _jobStatusDone = MediatorLiveData<Boolean>()
val jobStatusDone: LiveData<Boolean>
    get() = _jobStatusDone

private val _counterparties = MediatorLiveData<List<Counterparty>>()


override fun onReceive(context: Context?, intent: Intent?) {
    AndroidInjection.inject(this, context)

        val source = jobsRepository.getFulljobs()
        _jobStatusDone.addSource(source) {
            System.out.println("IT NEVER REACHES THIS PLACE.")
        }
    }
}

}

It's interesting because updating/inserting works.

EDIT: I would like to point that code I posted here, works in ViewModel's classes.

pjp
  • 157
  • 1
  • 12
  • surely this line is blocking `val source = jobsRepository.getFulljobs()`, so once you "observe" - (`addSource(source)`), the change has already occurred so `OnChanged` won't be called. Never used `LiveData` so I could be wrong. – Mark Jan 19 '19 at 13:27

2 Answers2

0

I am not sure on Kotlin version of MediatorLiveData implementation, but in Java version, you would need to implement onChanged() to get data. You may want to refer this thread. Hope this helps !

https://stackoverflow.com/a/44471378/1992013

Birender Singh
  • 513
  • 6
  • 16
  • "you would need to implement onChanged()" - its inside the `(source) { // lambda }` – Mark Jan 19 '19 at 13:29
0

I am not sure why you have to use MediatorLiveData at other places. You can actually use MutableLiveData and observe it where every you want.

Checkout my implementation of MVVM to see how its working.

Kotlin-MVVM-Demo

Guru
  • 286
  • 3
  • 6