on question not sure if you know the reason: so i...
# coroutines
p
on question not sure if you know the reason: so in android we use StateFlow and usually we use MutableStateFlow but the fragment only has the readonly so we created a function like this
Copy code
val <T> MutableStateFlow<T>.readOnly
    get() = this as StateFlow<T>
now I realised there is a function called asStateFlow() but when you go into asStateFlow the function does something different
Copy code
public fun <T> MutableStateFlow<T>.asStateFlow(): StateFlow<T> =
    ReadonlyStateFlow(this, null)
m
The
ReadonlyStateFlow
is so consumers of the flow cannot cast back to
MutableStateFlow
and change the values. Similar to
unmodifiableList
in Java.
🙌 1
p
what would you do @mkrussel? cast or asStateFlow
m
I would go with
asStateFlow
p
ok it’s funny cus there docs also have comments like
Copy code
// Backing property to avoid state updates from other classes
    private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList()))
m
But the cast would be a bit more performant and if you trust the consumers not to cast back then it would be just as safe
p
that’s why I’m asking cus the thing is per state and shareflow we would create an extra object
m
The backing property is needed for both solutions. One is more paranoid then the other, but both accomplish the desired goal.
My thought is one object is tiny, but others are more conservative about memory.
p
thanks @mkrussel really nice to share 🙂 have a nice day
a
"one object is tiny" but no object is free. 🙂 Tiny * 1000 is not so tiny anymore. 0 * 1000 is 0.
On mobile, "little" CPU cores execute instructions in order. Indirection is a lot more expensive than it looks. Performance death by a thousand cuts because all of your code is just a little bit inefficient is very real.
When doing the more efficient thing is no more cumbersome than being inefficient, there's no good reason not to form and exercise good habits.
p
thanks @Adam Powell for your opinion we actually decided to go with my simple extension function
Copy code
val <T> MutableStateFlow<T>.readOnly
    get() = this as StateFlow<T>
since we use sharedflow and sateflow everywhere and if we sum up it could have impact on a long run.