Hello, World! Is there an easy way to implement `M...
# flow
b
Hello, World! Is there an easy way to implement
MutableStateFlow
? For instance, does something similar to
callbackFlow {}
exist?
g
What you trying to achieve?
b
Hi! I'd like to expose some kind of persisted data (Android's SharedPreferences) as
MutableStateFlow
s
I managed to do it by having a wrapped
MutableStateFlow
but that involves quite a bit of boilerplate
b
You can transform any flow (e.g. callbackFlow) into StateFlow via flow.stateIn
b
oh! Thanks a lot, let me have a look.
oh but that creates a non mutable
StateFlow
though - my need is for a mutable one.
g
yep, you cannot return data back using stateIn
I think the easiest solution is just create a standard MutableStateFlow() and allow update it from two sides
You can do something like this:
Copy code
class FlowPreferences {
    private val flows = HashMap<String, MutableStateFlow<Any>>()
    private val sharedPreferences = TODO()
    private val someScope: CoroutineScope = TODO("Lifecycle of this scope really depends on your case, it can be just GlobalScope, if preferences are global")
    fun stringFlow(key: String): MutableStateFlow<String> {
        flows.getOrPut(key) {
            MutableStateFlow<String>(sharedPreferences.getString(key)).apply {
                someScope.launch {
                    collect {
                        if (sharedPreferences != it) {
                            sharedPreferences.edit().putString(it).apply()
                        }
                    }
                }
                //TODO: it also possible observe sharedPreferences and update flow
            }
        }
    }
}
Though, I’m not sure that having hot flows for this case is right solution, I would just replace this with non-mutable StateFlow and additional method for update, yes, a bit more code, but easier to maintain and clear separation of observable state from updating of this state (they also could be parts of separate interfaces)
b
Thanks a lot, interesting approach!
r
really interesting! Benoit
👍 1