Search code examples
androidkotlinandroid-livedatacoroutinemutablelivedata

CoroutineLiveData Builder repository not being invoked


I'm trying to use the new liveData builder referenced here to retrieve my data, then transform it into view models. However, my repository code isn't being invoked (at least I'm not able to see it being triggered when I use my debugger). Am I not supposed to use two liveData{ ... } builders? (one in my repository, one in my view model)?

class MyRepository @Inject constructor() : Repository {

    override fun getMyContentLiveData(params: MyParams): LiveData<MyContent> =
    liveData {

        val myContent = networkRequest(params) // send network request with params
        emit(myContent)
    }
}


class MyViewModel @Inject constructor(
    private val repository: MyRepository
) : ViewModel() {

    val viewModelList = liveData(Dispatchers.IO) {
        val contentLiveData = repository.getContentLiveData(keyParams)
        val viewModelLiveData = contentToViewModels(contentLiveData)
        emit(viewModelLiveData)
}

    private fun contentToViewModels(contentLiveData: LiveData<MyContent>): LiveData<List<ViewModel>> {
        return Transformations.map(contentLiveData) { content ->
            //perform some transformation and return List<ViewModel>
        }
    }
}

class MyFragment : Fragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory
    val myViewModel: MyViewModel by lazy {
        ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
    }

    lateinit var params: MyParams

    override fun onAttach(context: Context) {
        AndroidSupportInjection.inject(this)
        super.onAttach(context)
        myViewModel.params = params
        myViewModel.viewModelList.observe(this, Observer {
            onListChanged(it) 
        })

    }

Solution

  • You could try with the emitSource:

    val viewModelList = liveData(Dispatchers.IO) {
        emitSource(
            repository.getContentLiveData(keyParams).map {
                contentToViewModels(it)
            }
    }