【发布时间】:2020-09-18 06:44:19
【问题描述】:
我正在使用 MVVM 架构创建应用程序,但遇到了获取要在视图中显示的 LiveData 列表的问题。
在我的 ViewModel 中,我有一个 getAll() 函数,它使用 Room 从数据库中检索字符串列表。从那里,我得到字符串并调用我的 Retrofit 函数将每个字符串单独发送到返回对象的 Web 服务器。这是我的问题发生的地方。
从我在网上看到的 MVVM 教程中,它们通常具有 LiveData> 样式,但由于我单独获取每个对象,因此它变为 List> 但我认为这不是正确的做法,因为在我的查看我需要执行 ForEach 循环来观察列表中的每个 LiveData 对象。
我尝试了其他解决方法,但似乎不起作用。有更好的方法吗?
道
@Query("SELECT * FROM table")
fun getAll(): LiveData<List<String>>
存储库
fun getAll(): LiveData<List<String>> {
return dao.getAll()
}
fun getRetrofitObject(s: String): LiveData<RetrofitObject> {
api = jsonApi.getRetrofitObjectInfo(s, API_KEY)
val retrofitObject: MutableLiveData<RetrofitObject> = MutableLiveData()
api.enqueue(object : Callback<RetrofitObject> {
override fun onFailure(call: Call<RetrofitObject>?, t: Throwable?) {
Log.d("TEST", "Code: " + t.toString())
}
override fun onResponse(call: Call<RetrofitObject>?, response: Response<RetrofitObject>?) {
if (response!!.isSuccessful) {
retrofitObject.value = response.body()
}
}
})
return retrofitObject
}
MainActivityViewModel(视图模型)
var objectList ArrayList<LiveData<retrofitObject>> = ArrayList()
// This is getting objects using Retrofit
fun getRetrofitObject(s: String): LiveData<retrofitObject> {
return repo.getRetrofitObject(s)
}
// This is getting all the strings from the internal database
fun getAll(): ArrayList<LiveData<retroFitObject>> {
repo.getAll().value?.forEach {it ->
objectList.add(getRetrofitObject(it)) //How else would I be able to do this?
}
return objectList
}
MainActivity(视图)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityViewModel.getAll().forEach {
it.observe(this, Observer {it ->
mainActivityViewModel.objectList.add(it) //Here is part of the issue since I don't want to use a forloop in the View
})
}
adapter.objectList = mainActivityViewModel.objectList
recyclerView.adapter = adapter
}
谢谢,如果有其他需要或困惑,请告诉我!
【问题讨论】:
-
你试过
List<>而不是Arraylist<>吗? -
是的,我有@DetainedDeveloper
标签: android kotlin mvvm retrofit android-livedata