Last active
March 28, 2018 05:30
-
-
Save Reyurnible/02f288b7890769f90154876d1735fc78 to your computer and use it in GitHub Desktop.
RxSwift's Variable.swfit convert to Kotlin
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.Observable | |
import io.reactivex.subjects.BehaviorSubject | |
/** | |
* Wrapping Rx BehaviorSubject defaultValue object. | |
* RxSwfit Variable.swfit https://github.com/jspahrsummers/RxSwift/blob/master/RxSwift/SpinLock.swift | |
*/ | |
class Variable<T> private constructor(defaultValue: T?) { | |
companion object { | |
fun <T> create(): Variable<T> = Variable(null) | |
fun <T> createDefault(value: T): Variable<T> = Variable(value) | |
} | |
// Call onNext is toSerialized() | |
val isAsyncEmit: Boolean = true | |
// Value holder | |
private val subject: BehaviorSubject<T> = defaultValue?.let { | |
BehaviorSubject.createDefault(it) | |
} ?: BehaviorSubject.create() | |
var value: T | |
set(value) { | |
if (isAsyncEmit) subject.toSerialized().onNext(value) | |
else subject.onNext(value) | |
} | |
get() = if (subject.hasValue()) { | |
subject.value | |
} else { | |
throw IllegalStateException("Variable has no valueOrDefault.") | |
} | |
fun valueOrNull(): T? = if (subject.hasValue()) { | |
subject.value | |
} else { | |
null | |
} | |
fun valueOrDefault(defaultItem: T): T = subject.blockingFirst(defaultItem) | |
fun asObservable(): Observable<T> = subject.hide() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment