【发布时间】: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