您好我有一个从数据源检索的项目列表,然后我在observable上应用地图将数据存储到ROOM中。
它设法将它添加到表中,但是当我尝试检索它的LiveData时,它似乎没有通知我的观察者结果。
表中有明确的数据,我的查询工作正如我将从LiveData的返回时间更改为简单的List并且工作得非常好
这是我的数据类
@Entity
data class Item(
@PrimaryKey
val id:String,
val title: String,
val description: String,
val imgUrl: String,
val usageRules : List<String>,
)
这是我的DAO,它公开了一个添加了所有项目列表的函数
@Dao
interface MyDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveAllItems(itemList: MutableList<Item>)
@Query("SELECT * FROM items")
fun getAllItems(): LiveData<MutableList<Item>>
}
我的数据库课程
@Database(entities = arrayOf(Item::class), version = 1, exportSchema = false)
@TypeConverters(UsageRulesTypeConverter::class)
abstract class MyDatabase : RoomDatabase() {
abstract fun getProductDao(): MyDao
}
以下是我如何将数据插入数据库:
@Inject
lateInt val database : MyDatabase
override fun getAllItems(): Single<LiveData<MutableList<Item>>> {
//retrieve new data using rertrofit
networkController.getItems().map { responseItems ->
saveAllItems(responseItems )
getItems()
}
@Transaction
fun saveAllItems(allItems: ItemsDataSource) {
database.getProductDao().saveAllItems(allItems.loadedItems)
database.getProductDao().saveAllItems(allItems.savedItems)
database.getProductDao().saveAllItems(allItems.expiredItems)
database.getProductDao().saveAllItems(allItems.unloadedItems)
}
fun getItems() : LiveData<MutableList<Item>>{
return database.getProductDao().getAllItems()
}
我的数据源检索了4个项目列表,然后我将它们全部保存在一个实体/表中,但LiveData没有通知我的UI有关它的信息?
视图模型:
override fun getUnloadedOffers(): LiveData<MutableList<ProductOffer>> {
if (!this::itemsLiveData.isInitialized) {
itemsLiveData= MutableLiveData()
//get data from network or database
itemDelegator.getItems()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ items->
itemsLiveData= items
})
}
return itemsLiveData
}
UI
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
viewModel.getItems().observe(this, Observer {
items->
items?.let {
adapter = SomeAdapter(items)
itemsRecyclerView.adapter = adapter
adapter.notifyDataSetChanged()
}
})
答案 0 :(得分:2)
你的函数getUnloadedOffers()
是否返回空mutableList?我不确定将items
传递给itemsLiveData
是否会起作用,因为观察LiveData正在bg线程上运行(如果我没有弄错的话)
答案 1 :(得分:0)
保存数据集时,请尝试使用vararg
代替List
。
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveAllItems(vararg itemList: Item)
然后,您可以在列表中使用*
(也称为Spread Operator
)来调用此方法,就像这样
saveAllItems(*responseItems.toTypedArray())