All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.objectbox.kotlin.Flow.kt Maven / Gradle / Ivy

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()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy