【问题标题】:CoroutineLiveData Builder repository not being invokedCoroutineLiveData Builder 存储库未被调用
【发布时间】:2020-02-29 06:34:31
【问题描述】:

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

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

    }

【问题讨论】:

  • 您似乎正在设置一个LiveData 来发出另一个LiveData。这似乎很奇怪。应该是val viewModelList = contentToViewModels(repository.getContentLiveData(keyParams))
  • 我试试看。
  • @CommonsWare 那没用。该存储库仍被完全跳过。
  • 您可能还想看看 emitSource 的东西 - 它似乎是为您量身定做的 :) developer.android.com/topic/libraries/architecture/coroutines

标签: android kotlin android-livedata coroutine mutablelivedata


【解决方案1】:

你可以试试emitSource:

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

【讨论】:

  • 是的,这是缺少的部分。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
相关资源
最近更新 更多