0

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

    }
VIN
  • 6,385
  • 7
  • 38
  • 77
  • You seem to be setting up a `LiveData` to emit another `LiveData`. That seems odd. Should that be `val viewModelList = contentToViewModels(repository.getContentLiveData(keyParams))`? – CommonsWare Nov 03 '19 at 22:11
  • I'll give that a try. – VIN Nov 03 '19 at 22:15
  • @CommonsWare That didn't work. The repository is still being skipped entirely. – VIN Nov 03 '19 at 22:19
  • 1
    You also might want to take a look at the `emitSource` thingie - it seems like it's made for you :) https://developer.android.com/topic/libraries/architecture/coroutines – r2rek Nov 04 '19 at 09:12

1 Answers1

1

You could try with the emitSource:

val viewModelList = liveData(Dispatchers.IO) {
    emitSource(
        repository.getContentLiveData(keyParams).map {
            contentToViewModels(it)
        }
}
r2rek
  • 2,083
  • 13
  • 16