objectbox-java icon indicating copy to clipboard operation
objectbox-java copied to clipboard

Enable DataObserver to observe T?, not only List<T>

Open Ditscheridou opened this issue 4 years ago • 2 comments

I came across the DataObservers today and noticed, that when you call subscribe on a Query<T>, you will end in a List<T> as result which in my opinion is not what you want, e.g. if you want to find an entity by its id BUT also want to track the changes of this object, you would normally do this: boxStore.boxFor(T::class.java).query {}.findFirst() which would result in a T? result type. Now when i also want to track changes here, i wrap it in a flow (i use kotlin) like this:

@ExperimentalCoroutinesApi
fun <T> Query<T>.asFlow() = callbackFlow {
    val subscription =
        [email protected]()
            .onError { cancel("Database error", it) }
            .observer { data -> offer(data) }
    awaitClose { subscription.cancel() }
}

Suddenly i have to deal with a List<T> due to the fact, that the SubscriptionBuilder returns a SubscriptionBuilder<List<T>>.

Please add a more precise way to differ between single and multiple values. Currently i need to implement workarounds for this, but that should be a standard behaviour

Ditscheridou avatar May 28 '21 08:05 Ditscheridou

Try to use a general observer (internally query observers just wrap around these). https://docs.objectbox.io/data-observers-and-rx#observing-general-changes

greenrobot-team avatar May 31 '21 13:05 greenrobot-team

What should I do if I use RxJava Extension Library? Could you add the following functions to QueryBuilder?

boxFor(Day.class).query(Day_.date.equal(date.toEpochDay())
                        .unique()  // or .first()
                        .build())

And in the Query class leave only the function find(). I think that such syntax could make it easier for many to work with Data Observers & Rx.

evkost avatar Sep 07 '22 15:09 evkost