Skip to content

Instantly share code, notes, and snippets.

@hleinone
Created February 6, 2019 09:10
Show Gist options
  • Save hleinone/2c4119eaf4a7ee423ff3ecc46eb32704 to your computer and use it in GitHub Desktop.
Save hleinone/2c4119eaf4a7ee423ff3ecc46eb32704 to your computer and use it in GitHub Desktop.
Android SharedPreferences Rx extension
import android.content.SharedPreferences
import io.reactivex.Maybe
import io.reactivex.Single
@androidx.annotation.CheckResult
fun SharedPreferences.boolean(key: String, defValue: Boolean): Single<Boolean> = Single.just(getBoolean(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.boolean(key: String): Maybe<Boolean> = Maybe.create { maybeEmitter ->
if (contains(key)) {
maybeEmitter.onSuccess(getBoolean(key, false))
}
maybeEmitter.onComplete()
}
@androidx.annotation.CheckResult
fun SharedPreferences.float(key: String, defValue: Float): Single<Float> = Single.just(getFloat(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.float(key: String): Maybe<Float> = Maybe.create { maybeEmitter ->
if (contains(key)) {
maybeEmitter.onSuccess(getFloat(key, -1f))
}
maybeEmitter.onComplete()
}
@androidx.annotation.CheckResult
fun SharedPreferences.int(key: String, defValue: Int): Single<Int> = Single.just(getInt(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.int(key: String): Maybe<Int> = Maybe.create { maybeEmitter ->
if (contains(key)) {
maybeEmitter.onSuccess(getInt(key, -1))
}
maybeEmitter.onComplete()
}
@androidx.annotation.CheckResult
fun SharedPreferences.long(key: String, defValue: Long): Single<Long> = Single.just(getLong(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.long(key: String): Maybe<Long> = Maybe.create { maybeEmitter ->
if (contains(key)) {
maybeEmitter.onSuccess(getLong(key, -1L))
}
maybeEmitter.onComplete()
}
@androidx.annotation.CheckResult
fun SharedPreferences.string(key: String, defValue: String): Single<String> = Single.just(getString(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.stringSet(key: String, defValue: Set<String>): Single<Set<String>> = Single.just(getStringSet(key, defValue))
@androidx.annotation.CheckResult
fun SharedPreferences.string(key: String): Maybe<String> = Maybe.create { maybeEmitter ->
getString(key, null)?.let {
maybeEmitter.onSuccess(it)
}
maybeEmitter.onComplete()
}
@androidx.annotation.CheckResult
fun SharedPreferences.stringSet(key: String): Maybe<Set<String>> = Maybe.create { maybeEmitter ->
getStringSet(key, null)?.let {
maybeEmitter.onSuccess(it)
}
maybeEmitter.onComplete()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment