Skip to content

Instantly share code, notes, and snippets.

@Reyurnible
Last active March 28, 2018 05:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reyurnible/02f288b7890769f90154876d1735fc78 to your computer and use it in GitHub Desktop.
Save Reyurnible/02f288b7890769f90154876d1735fc78 to your computer and use it in GitHub Desktop.
RxSwift's Variable.swfit convert to Kotlin
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