Skip to content

Instantly share code, notes, and snippets.

@bnorm
Created October 18, 2017 13:00
Show Gist options
  • Save bnorm/b2563fe2a0859d063d7a9be54638d79e to your computer and use it in GitHub Desktop.
Save bnorm/b2563fe2a0859d063d7a9be54638d79e to your computer and use it in GitHub Desktop.
Turn a RxJava Single or Maybe into a Kotlin delegate
import io.reactivex.Maybe
import io.reactivex.Single
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
operator fun <T> Single<T>.provideDelegate(thisRef: Any?, property: KProperty<*>): ReadOnlyProperty<Any?, T> {
return SingleDelegate(this)
}
private class SingleDelegate<out T>(single: Single<T>) : ReadOnlyProperty<Any?, T> {
private val delegate = single.cache()
init {
delegate.subscribe()
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return delegate.blockingGet()
}
}
operator fun <T> Maybe<T>.provideDelegate(thisRef: Any?, property: KProperty<*>): ReadOnlyProperty<Any?, T?> {
return MaybeDelegate(this)
}
private class MaybeDelegate<out T>(maybe: Maybe<T>) : ReadOnlyProperty<Any?, T?> {
private val delegate = maybe.cache()
init {
delegate.subscribe()
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return delegate.blockingGet()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment