https://kotlinlang.org logo
#coroutines
Title
# coroutines
f

FunkyMuse

01/14/2021, 8:01 AM
Hello devs, which one do you think it's better to be used and why? 1. private val stateData = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> get() = stateData Or 2. private val stateData = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> = stateData
l

Lukas Sztefek

01/14/2021, 8:07 AM
It’s just about you convention and personal taste. I prefer:
Copy code
private val stateData = MutableStateFlow(State.Idle)
val state: StateFlow<State> = stateData.asStateFlow()
The only reason – I don’t like syntax of getters and setters in kotlin.
⏸️ 2
K 2
j

Javier

01/14/2021, 8:08 AM
asStateFlow doesn't let you cast to MutableStateFlow I think, so it is even better
f

FunkyMuse

01/14/2021, 8:08 AM
That's a sweet solution too, i was wondering whether the getter has a performance impact rather than a plain val
l

Lukas Sztefek

01/14/2021, 8:09 AM
I doubt it.
j

Javier

01/14/2021, 8:13 AM
it should crash, but I didn't try it personally
f

FunkyMuse

01/14/2021, 8:16 AM
It won't crash, I've tried both solutions i wrote above, I'm just wondering if the getter is slower due to it not holding the data once the mutable one is created but only when it's called and whether this imposes a space complexity since the val of immutable state flow is immediately created after the mutable state flow
j

Javier

01/14/2021, 8:20 AM
I am not talking about get or assignment
I am taking about using asStateFlow or not
and trying to recast it to MutableStateFlow
f

FunkyMuse

01/14/2021, 8:24 AM
You're not casting it to MutableStateFlow You're exposing it as immutable StateFlow
j

Javier

01/14/2021, 8:32 AM
yeah, I know
but if someone is mad, can try to cast it as MutableStateFlow
sample:
Copy code
// ViewModel

private val _state = MutableStateOf(...)
val _state: StateFlow<> = _state


// Fragment

(viewModel.state as MutableStateFlow).value = ...
f

FunkyMuse

01/14/2021, 8:35 AM
Oh well that's a mistake right there hah, I don't think this should be a matter of discussion? Don't get me wrong, I'm trying not to stir this discussion aside
j

Javier

01/14/2021, 8:35 AM
Someone said me that using
asStateFlow
you can't do that because it should crash. But I have never tried that casting personally, with our without
asStateFlow
It should because it can be an additional argument to use
asStateFlow
instead of the other one
r

Ruckus

01/14/2021, 3:39 PM
@FunkyMuse As an unrelated note, it's considered bad form to @ someone for a generic question like this that can be answered by anyone. There's no reason to expect Roman to personally answer your questions. You should probably refrain from doing it in the future, unless you really do need to specifically address that person.
K 1
5 Views