objectbox / objectbox-java

Android Database - first and fast, lightweight on-device vector database
https://objectbox.io
Apache License 2.0
4.36k stars 301 forks source link

[Paging3] ObjectBox returns all items and ignores PagingConfig.pageSize #1083

Closed fcat97 closed 2 years ago

fcat97 commented 2 years ago

Getting all the elements from database at once just like normal query. ObjectBox implementation of PagingDataSource completely ignores PageConfig.pageSize value.

The documentation is outdated. Besides it only describes how to add Paging2 with ObjectBox.

Basic info:

Code

Entity


@Entity
class Trx {
@Id var id: Long = 0
@Index
var trxID: String = UUID.randomUUID().toString()

var label: String = ""

var note: String = ""

var amount: Float = 0f

}


> Repository
```kotlin
LocalDatabaseImpl(
    // dependencies...
    private val trxBox: Box<Trx>
) {
    override fun getPagingDataSource(): ObjectBoxDataSource.Factory<Trx> {

        val query = trxBox.query().build()

        return ObjectBoxDataSource.Factory(query)
    }
}

ViewModel

@HiltViewModel
class HomeViewModel @Inject constructor(
private val db: LocalDatabase
): ViewModel() {
private val pager: Pager<Int, Trx> 
get() = Pager(
config = PagingConfig(pageSize = 100),
pagingSourceFactory = db.getPagingDataSource()
.asPagingSourceFactory(Dispatchers.IO)
)
private var _trxFlow = pager.flow.cachedIn(viewModelScope)
val trxFlow: Flow<PagingData<Trx>> get() = _trxFlow
}

UI composable


@Composable
fun TrxContent() {
// ... 
val trxItems = viewModel.trxFlow.collectAsLazyPagingItems()

// latest trx
LazyColumn () {
    items(items = trxItems) { trx ->
        if (trx == null) return@items

        Log.d(TAG, "Content: ${trxItems.itemCount}") // getting 10,000 every time

        ItemTrxCompose(trx)
    }
}

}

greenrobot-team commented 2 years ago

@fcat97 Thanks. Is it possible that trxItems.itemCount returns the total amount of items and not the ones that are just loaded? The ObjectBoxDataSource implementation has not changed, so I'm not sure how that could be the issue.

Regardless, there is no DataSource written for Paging 3, yet.

fcat97 commented 2 years ago

Thanks. I missed the internal documentation.

// ---------------------
// LazyPageItems.Kt
// ---------------------
/**
* The number of items which can be accessed.
*/
val itemCount: Int get() = itemSnapshotList.size

// ---------------------
// ItemSnapshotList.kt
// ---------------------
/**
* Size of ItemSnapshotList including placeholders.
* To get the size excluding placeholders, use List.size on items directly.
*/
public override val size: Int
        get() = placeholdersBefore + items.size + placeholdersAfter

Instead of trxItems.itemCount I need to call trxItems.itemSnapshotList.items.size. It shows the actual loaded items, at first it loads 300 items and then loads according to pageSize.