Skip to content

Instantly share code, notes, and snippets.

@gotev
Created May 27, 2019 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotev/022ec6a7b41a12ddd2270c3fd7320507 to your computer and use it in GitHub Desktop.
Save gotev/022ec6a7b41a12ddd2270c3fd7320507 to your computer and use it in GitHub Desktop.
Optional Subject
import io.reactivex.subjects.BehaviorSubject
class Optional<T>(private val value: T? = null) {
companion object {
fun <T> subject() = BehaviorSubject.createDefault(Optional<T>())
}
fun isPresent() = value != null
fun value() = value
}
fun <T> BehaviorSubject<Optional<T>>.currentValue() = value?.value()
fun <T> BehaviorSubject<Optional<T>>.isSet() = value?.isPresent() ?: false
fun <T> BehaviorSubject<Optional<T>>.clearValue() = onNext(Optional())
fun <T> BehaviorSubject<Optional<T>>.setValue(value: T) = onNext(Optional(value))
@gotev
Copy link
Author

gotev commented May 31, 2019

Swift:

import Foundation
import RxSwift
import RxCocoa
import SkySelfCare

extension BehaviorRelay {
    func cachedValue<T>(forceFetchIf: (_ value: T) -> Bool = { _ in false },
                        ifNullFetchFrom: () -> Single<T>) -> Single<T> where Element == T? {
        if let value = value, !forceFetchIf(value) {
            return Single.just(value)
        } else {
            return ifNullFetchFrom().do(onSuccess: { result in
                self.accept(result)
            })
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment