CoroutineLiveData Builder存储库未被调用

问题描述 投票:0回答:2

我正在尝试使用引用为here的新liveData构建器来检索我的数据,然后将其转换为视图模型。但是,我的存储库代码没有被调用(至少在使用调试器时,我看不到它被触发)。我不应该使用两个liveData{ ... }构建器吗? (一个在我的存储库中,一个在我的视图模型中)?

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

    }
android kotlin android-livedata coroutine mutablelivedata
2个回答
0
投票

发布您的片段类的完整代码。以及为什么要使用地图?返回livedata,您假设正在使用switchMap()返回liveData


0
投票

您可以尝试使用emitSource

val viewModelList = liveData(Dispatchers.IO) {
    emitSource(
        repository.getContentLiveData(keyParams).map {
            contentToViewModels(it)
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.