io.objectbox.kotlin.Flow.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of objectbox-kotlin Show documentation
Show all versions of objectbox-kotlin Show documentation
ObjectBox is a fast NoSQL database for Objects
The newest version!
package io.objectbox.kotlin
import io.objectbox.BoxStore
import io.objectbox.query.Query
import io.objectbox.reactive.SubscriptionBuilder
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
/**
* Like [SubscriptionBuilder.observer], but emits data changes to the returned flow.
* Automatically cancels the subscription when the flow is canceled.
*
* For example to create a flow to listen to all changes to a box:
* ```
* store.subscribe(TestEntity::class.java).toFlow()
* ```
*
* Or to get the latest query results on any changes to a box:
* ```
* box.query().subscribe().toFlow()
* ```
*/
@ExperimentalCoroutinesApi
fun SubscriptionBuilder.toFlow(): Flow = callbackFlow {
val subscription = [email protected] {
trySendBlocking(it)
}
awaitClose { subscription.cancel() }
}
/**
* Shortcut for `BoxStore.subscribe(forClass).toFlow()`, see [toFlow].
*/
@ExperimentalCoroutinesApi
fun BoxStore.flow(forClass: Class): Flow> = this.subscribe(forClass).toFlow()
/**
* Shortcut for `query.subscribe().toFlow()`, see [toFlow].
*/
@ExperimentalCoroutinesApi
fun Query.flow(): Flow> = [email protected]().toFlow()