Hey guys, I have a really random question that’s k...
# random
s
Hey guys, I have a really random question that’s kinda bugging me, is it really necessary to wrap a
SharedPreference
operation with a
Rx
call? kinda something like
Copy code
fun save(key: String, value: String) {
        sharedPreferences.edit().putString(key, value).apply()
    }

    fun saveSingle(key: String, value: String): Single<String> = Single.create {
        try {
            save(key, value)
            it.onSuccess(value)
        } catch (e: Exception) {
            it.onError(Failure.Error(e.localizedMessage))
        }
    }
g
it’s necessary only if you want to have Rx interface for this function
s
ok, thanks not sure I would though
g
But this implementation doesn’t make a lot of sense, because apply() is asynchronous save, so you even don’t know when it actually happened. commit() makes a bit more sense, but it’s blocking operation so you probably done it on IO scheduler
s
excellent thanks
g
Also instead of Single.create you can just use
Single.fromCallable
, which is mostly the same, but without wrapping to
Failure.Error
also I believe such wrapping to
Failure.Error
is bad style, because you lose stack trace and cause of exception
s
never knew about the
Single.fromCallable
will check it out as well
g
This is just static builder function that wraps any blocking code to Rx primitives like Single. Emits onNext or onError if code inside of builder throws an exception
s
wow, thanks very much
d
Shared preferences is basically a fancy wrapper for a big
Map
(over simplification I know) so it can be used from the main thread without issue. That said though it is not a database so be very careful with how much you store in it.