Inconvenient Kotlin extension functions for Kotlin Flows
Extensions for Kotlin Flow is inconvenient to use in some cases
Most of my Realm queries already return Kotlin Flows with custom code and while I was trying to migrate my codebase to V10 Realm extensions, I've noticed some quirks.
findAllAsync() with first() is problematic:
I like to have my Realm queries async so I mostly use .findAllAsync(). On the other hand, I have many usecases where I only need the first object, so I call .first() on those flows. The docs says, that this is the intended use for that scenario, but I get basically nothing, since fun <T : RealmModel> RealmResults<T>.toFlow(): Flow<RealmResults<T>> does offer(freeze()) the initial RealmResults, making the .first() operator pretty much useless in this case. Even the docs of .findAllAsync() states this:
Returns: immediately an empty RealmResults. Users need to register a listener RealmResults.addChangeListener(RealmChangeListener) to be notified when the query completes.
I would say calling .drop(1) makes me itch. :) I don't know what should be the proper solution here, because both findAll() and findAllAsync() returns with RealmResults that the extension is for.
Objects in a flow are frozen, so I can't modify them.
I have some usecases where I only need the first element from a flow, and I want to modify it. It would be nice to have some first party extensions to have a detached object available. I've ended up with these for myself:
fun <T : RealmModel> T.copyFromRealm(): T = Realm.getDefaultInstance().use {
it.copyFromRealm(this)
}
fun <T : RealmModel> RealmResults<T>.copyFromRealm(): List<T> = Realm.getDefaultInstance().use { realm ->
map { realm.copyFromRealm(it) }
}
fun <T : RealmModel> Flow<RealmResults<T>>.copyFromRealm(): Flow<List<T>> = map {
val config = it.realm.configuration
return@map Realm.getInstance(config).use { flowRealm ->
flowRealm.copyFromRealm(it)
}
}
Handling nullability of findFirst() is inconvenient
Problem is that the return of .findFirst() is nullable, and it makes your code ugly. I have something like this in my code now:
val myObjectFlow: Flow<MyObject?> = realm.where<MyObject>()
.contains("Name", name, Case.INSENSITIVE)
.findFirst()
?.toFlow() ?: flowOf(null)
I think it would be nice to have the extension function like this:
fun <T : RealmModel> T?.toFlow(): Flow<T?>
and in case of this is null, return with flowOf(null)
Hi @datikaa . Thank you for the feedback. I'll try to respond to each individually.
findAllAsync() with first() is problematic: This behavior is identical to the behavior we have for RxJava Flowables, and I believe we have it, so components listening to a flow don't have to wait too long for an initial element which can cause a few issues for UI components that then have to deal with "un-initialized" state a lot more. But you are not the first to have brought this up as problematic behavior.
For RxJava we also provide a RxObservableFactory interface that allows you to customize the Flowables, which allows for an easy to way to e.g. drop all first emissions. I'm not 100% sure if we can use the same approach here though as the Coroutine Flows are supported through extension functions.
Objects in a flow are frozen, so I can't modify them. This is by design as we otherwise cannot pass items through different threads and are in line with general recommendations of only having immutable data in event streams. That said, we should support making it easier to get an in-memory copy that can be managed.
Again, this point to that we need to find a way for you to customize the flows we are creating.
Handling nullability of findFirst() is inconvenient This looks like an oversight on our end, we should just add that extension.
Hi @cmelchior!
Thanks for your reply!
About findAllAsync() with first() is problematic:
I think that the documentation of findAllAsync() just needs to include this behaviour, and simply .dropWhile { !it.isLoaded } can be used to filter out any offers that are not loaded.
In this case the docs should look like this:
val foo = realmInstance.where(Foo::class.java)
.findAllAsync()
.toFlow()
.dropWhile { !it.isLoaded }
.first()
I've also noticed one more questionable thing in the docs. I think you can't use .flowOn(Dispatchers.IO) this simply, because RealmChangeListener requires a looper thread. If you use Dispatchers.IO this will be in the log:
`E/REALM_JNI: jni: ThrowingException 8, Realm accessed from incorrect thread. in /tmp/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_OsResults.cpp line 433, .
E/REALM_JNI: Exception has been thrown: Realm accessed from incorrect thread. in /tmp/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_OsResults.cpp line 433`
@datikaa Thanks again for your input. I have created an issue to fix the documentation, while trying to consider what would be the best way to unentangle the underlying looper/corountine context dependencies a bit in the same go: #7168
I have created some small extensions around toFlow() that makes my call sites easy. Here's my gist. My call site now looks like this, and I'm happy with it for now:
fun getFooFlow(name: String): Flow<List<Foo>> = autoCloseRealmFlow { realm ->
realm.where<Foo>()
.contains("name", name, Case.INSENSITIVE)
.flowAll()
}
I have abandoned findFirstAsync() because I can't check for isLoaded.
@datikaa Thank you for the feedback. I have created some issues based on it: #7164 and #7165 and hopefully you also got answers to your question. So I'll close this issue now. Feel free to reopen if you still think there are outstanding issues