Created
October 18, 2017 13:00
-
-
Save bnorm/b2563fe2a0859d063d7a9be54638d79e to your computer and use it in GitHub Desktop.
Turn a RxJava Single or Maybe into a Kotlin delegate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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