Skip to content

Instantly share code, notes, and snippets.

@ologe
Last active November 13, 2024 21:10
Show Gist options
  • Select an option

  • Save ologe/eaa1dea1f94cdda1a39adcaf3886658a to your computer and use it in GitHub Desktop.

Select an option

Save ologe/eaa1dea1f94cdda1a39adcaf3886658a to your computer and use it in GitHub Desktop.
Android shared preference observer using kotlin coroutines (1.3.0)
inline fun <reified T> SharedPreferences.observeKey(key: String, default: T): Flow<T> = channelFlow {
send(getItem(key, default))
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
if (key == k) {
trySend(getItem(key, default))
}
}
registerOnSharedPreferenceChangeListener(listener)
awaitClose {
unregisterOnSharedPreferenceChangeListener(listener)
}
}
inline fun <reified T> SharedPreferences.getItem(key: String, default: T): T {
@Suppress("UNCHECKED_CAST")
return when (default) {
is String -> getString(key, default) as T
is Int -> getInt(key, default) as T
is Long -> getLong(key, default) as T
is Boolean -> getBoolean(key, default) as T
is Float -> getFloat(key, default) as T
is Set<*> -> getStringSet(key, default as Set<String>) as T
else -> error("generic type not handled ${T::class.java.name}")
}
}
@ChairfaceChippendale

Copy link
Copy Markdown

What if getItem is suspend function?

@ologe

ologe commented Nov 30, 2020

Copy link
Copy Markdown
Author

implementation updated using MutableStateFlow instead of Channel

@neuhoffm

neuhoffm commented Aug 18, 2021

Copy link
Copy Markdown

Can I use parts of this code (giving credit of course) to support a class I'm teaching on migrating from Java to Kotlin?

@ologe

ologe commented Aug 18, 2021

Copy link
Copy Markdown
Author

@neuhoffm yeah sure feel free to use any gist from my profile and good luck ๐Ÿ˜„

@neuhoffm

Copy link
Copy Markdown

Awesome, thank you!

@gmk57

gmk57 commented Jun 27, 2022

Copy link
Copy Markdown

Thanks for the idea!
Are you sure flow.onCompletion part works as expected? According to the docs, StateFlow never completes.

Also, registerOnSharedPreferenceChangeListener has a warning that the listener might be garbage-collected prematurely.

@ologe

ologe commented Jun 27, 2022

Copy link
Copy Markdown
Author

Hi @gmk57! onCompletion seems to be called correctly, and I think that's because it's creating internally an unsafeFlow, but you can use a channelFlow as well

regarding the listener being garbage collected I never seen that warning, which version are you using? ๐Ÿค”

@gmk57

gmk57 commented Jun 27, 2022

Copy link
Copy Markdown

Indeed, onCompletion is triggered by the collector's cancellation:

@Test
fun testOnCompletion() = runBlocking {
    var onCompleteCalled = false
    MutableStateFlow("abc")
        .onCompletion { onCompleteCalled = true }
        .take(1).collect()
    assertTrue(onCompleteCalled)
}

This quirk is mentioned in the docs: "Unlike catch, this operator reports exception that occur both upstream and downstream and observe exceptions that are thrown to cancel the flow". I would say that onCompletion name is somewhat misleading. ;)

As for listener, I've seen it in the javadocs, at least for API 29-32.

@tkubasik-luna

Copy link
Copy Markdown
inline fun <reified T> SharedPreferences.observeKey(key: String, default: T?): Flow<T?> {
    val flow = MutableStateFlow(getItem(key, default))

    val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
        if (key == k) {
            try {
                flow.value = getItem(key, default)!!
            } catch (e: Exception) {
                flow.value = null
            }
        }
    }

    return flow
        .onCompletion { unregisterOnSharedPreferenceChangeListener(listener) }
        .onStart { registerOnSharedPreferenceChangeListener(listener) }
}

inline fun <reified T> SharedPreferences.getItem(key: String, default: T?): T? {
    @Suppress("UNCHECKED_CAST")
    return when (default) {
        is String? -> getString(key, default) as T?
        is Int -> getInt(key, default) as T
        is Long -> getLong(key, default) as T
        is Boolean -> getBoolean(key, default) as T
        is Float -> getFloat(key, default) as T
        is Set<*> -> getStringSet(key, default as Set<String>) as T
        else -> throw IllegalArgumentException("generic type not handle ${T::class.java.name}")
    }
}

Updated to take into account the null value (if no value is stored for this key)
Add register in the 'onStart' otherwise the flow was cancelled every recomposition :)

@gmk57

gmk57 commented Jan 24, 2023

Copy link
Copy Markdown

Hmm, @tkubasik-luna your version always produces Flow<T?> while the original one returned Flow<T>. We provide the default value, so the latter makes more sense to me. And it worked fine when no value is stored for the key, thanks to the default passed to getString, getInt, etc.

try/catch could potentially catch the "stored type does not match expected type" kind of errors, but in this case we fail earlier, on line 2. And it's probably good, because this type mismatch is clearly a programmer's mistake which should be fixed.

As for cancellation, in my testing both variants cancel/restart on every recomposition when called directly inside composable. I suppose it's inevitable since we're creating a new flow each time. But this is easily solved by wrapping prefs.observeKey() in remember, or better by moving it to a more stable place, e.g. ViewModel or Repository. ๐Ÿ˜ƒ

@mobilekosmos

Copy link
Copy Markdown

I came with this solution:

    private fun SharedPreferences.userIdFlow(key: String, defValue: String?): Flow<String?> = callbackFlow {
        var currentValue = getString(key, defValue)

        val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
            if (k == key) {
                val newValue = getString(key, defValue)
                if (newValue != currentValue) {
                    currentValue = newValue
                    trySend(newValue).isSuccess
                }
            }
        }

        registerOnSharedPreferenceChangeListener(listener)
        if (currentValue != null && currentValue!!.isNotEmpty()) {
            trySend(currentValue).isSuccess // emit current value immediately if not null and not empty
        }

        awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
    }

What's your analysis on it compared to yours?

@ubuntudroid

ubuntudroid commented Nov 11, 2024

Copy link
Copy Markdown

@mobilekosmos as MutableSet is always also a Set, your code would never return a MutableSet.

Then again: why would you want to put a MutableSet into SharedPreferences in the first place? It would lose its mutability anyway the moment you serialize. And when you return it, you actually only ever get an immutable set. Which one could then make a mutable set at the call site, if needed.

I would just remove that when branch altogether.

@ubuntudroid

Copy link
Copy Markdown

What I'm using now is kind of a mix between @ologe's and @mobilekosmos 's approach:

inline fun <reified T> SharedPreferences.observeKey(
    coroutineScope: CoroutineScope,
    coroutineContextProvider: CoroutineContextProvider,
    key: String,
    default: T,
): Flow<T> = callbackFlow {
    trySend(getItem(coroutineContextProvider, key, default))

    val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
        if (k == key) {
            coroutineScope.launch {
                trySend(getItem(coroutineContextProvider, key, default))
            }
        }
    }

    registerOnSharedPreferenceChangeListener(listener)

    awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
}.conflate()

suspend inline fun <reified T> SharedPreferences.getItem(
    coroutineContextProvider: CoroutineContextProvider,
    key: String,
    default: T,
): T = withContext(coroutineContextProvider.io) {
    @Suppress("UNCHECKED_CAST")
    when (default) {
        is String -> getString(key, default) as T
        is Int -> getInt(key, default) as T
        is Long -> getLong(key, default) as T
        is Boolean -> getBoolean(key, default) as T
        is Float -> getFloat(key, default) as T
        is Set<*> -> getStringSet(key, default as Set<String>) as T
        else -> throw IllegalArgumentException("generic type not handle ${T::class.java.name}")
    }
}

@ologe

ologe commented Nov 13, 2024

Copy link
Copy Markdown
Author

@ubuntudroid yeah probably handling MutableSet is not actually needed, I think the initial thought was that kotlin.collection.MutableSet translated into java.util.Set

btw about switching dispatcher, I think is unnecessary because if I remember correctly SharedPreferences is just a glorified HashMap, and everything is stored (additionally) in memory, the expensive part of the api is writing to disk


I'm also updating the gist to what I think is the cleanest way after almost 4 years ๐Ÿ˜„

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