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

app.cash.sqldelight.rx3.RxJavaExtensions.kt Maven / Gradle / Ivy

The newest version!
@file:JvmName("RxQuery")

package app.cash.sqldelight.rx3

import app.cash.sqldelight.Query
import io.reactivex.rxjava3.annotations.CheckReturnValue
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableEmitter
import io.reactivex.rxjava3.core.ObservableOnSubscribe
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.Optional
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Turns this [Query] into an [Observable] which emits whenever the underlying result set changes.
 *
 * @param scheduler By default, emissions occur on the [Schedulers.io] scheduler but can be
 * optionally overridden.
 */
@CheckReturnValue
@JvmOverloads
@JvmName("toObservable")
fun  Query.asObservable(scheduler: Scheduler = Schedulers.io()): Observable> {
  return Observable.create(QueryOnSubscribe(this)).observeOn(scheduler)
}

private class QueryOnSubscribe(
  private val query: Query,
) : ObservableOnSubscribe> {
  override fun subscribe(emitter: ObservableEmitter>) {
    val listenerAndDisposable = QueryListenerAndDisposable(emitter, query)
    query.addListener(listenerAndDisposable)
    emitter.setDisposable(listenerAndDisposable)
    emitter.onNext(query)
  }
}

private class QueryListenerAndDisposable(
  private val emitter: ObservableEmitter>,
  private val query: Query,
) : AtomicBoolean(),
  Query.Listener,
  Disposable {
  override fun queryResultsChanged() {
    emitter.onNext(query)
  }

  override fun isDisposed() = get()

  override fun dispose() {
    if (compareAndSet(false, true)) {
      query.removeListener(this)
    }
  }
}

@CheckReturnValue
fun  Observable>.mapToOne(): Observable {
  return map { it.executeAsOne() }
}

@CheckReturnValue
fun  Observable>.mapToOneOrDefault(defaultValue: T): Observable {
  return map { it.executeAsOneOrNull() ?: defaultValue }
}

@CheckReturnValue
fun  Observable>.mapToOptional(): Observable> {
  return map { Optional.ofNullable(it.executeAsOneOrNull()) }
}

@CheckReturnValue
fun  Observable>.mapToList(): Observable> {
  return map { it.executeAsList() }
}

@CheckReturnValue
fun  Observable>.mapToOneNonNull(): Observable {
  return flatMap {
    val result = it.executeAsOneOrNull()
    if (result == null) Observable.empty() else Observable.just(result)
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy