Home > Net >  Store Items in Room database with Flow
Store Items in Room database with Flow

Time:09-26

In my task I fetch Items from API and I need to store it into Room database.

This is my ItemDao:

@Query("SELECT * FROM item_table")
    fun getAllItems(): Flow<List<ItemLocal>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertItem(item: ItemLocal)

Repository: Here I map to ItemLocal from ItemResponse (api Item)

  suspend fun getItems(): List<ItemLocal> {
        return apiService.getItems()?.items?.map {
            ItemLocal(
                ItemId = "1",
                author = it.author.orEmpty(),
                title = it.title.orEmpty(),
            )
        } ?: emptyList()
    }

ViewModel:

private val _itemList = MutableStateFlow(emptyList<ItemLocal>())
viewModelScope.launch {
            _itemList.update {
                itemRepository.getItems()
            }
        }
fun addItemsToDatabase(items: List<ItemLocal>) = viewModelScope.launch {
        itemRepository.insertItemsToDatabase(items)
    }

MainActivity:

lifecycleScope.launch {
            viewModel.itemList.collect { listOfItems ->
                viewModel.addItemToDatabase(listOfItems)

            }
        }

This code only puts 1 Item (it should return more). I tried also in ViewModel with .forEach to put object by object but it also returns only 1 Item. I need to store all items to Room database.

Edit:

@Entity(tableName = "item_table")
data class ItemLocal(
    val author: String,
    @PrimaryKey(autoGenerate = false)
    val title: String,
)

CodePudding user response:

In the snippet, you use fixes "1" ItemId for each item provided by server, so Room database replace them one-by-one. To save all items, you should provide unique IDs for items (either manually or with autoincrement SQL option). Please, provide more info (LocalItem model) to clarify the case.

  • Related