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

streetsofboston

03/04/2021, 6:14 PM
Question: Why would this be preferred
Copy code
private val _myFlow = MutableStateFlow<String>("")
val myFlow: SharedFlow<String> = _myFlow.asStateFlow()
over
Copy code
private val _myFlow = MutableStateFlow<String>("")
val myFlow: SharedFlow<String> = _myFlow
? A MutableStateFlow is a StateFlow; why the extra call to
asStateFlow()
?
c

Charlie Christensen

03/04/2021, 6:18 PM
I'm not 100% sure but I think this makes sure it can't be casted into a
MutableStateFlow
by the consumer
l

louiscad

03/04/2021, 6:18 PM
Yes, that's what it does.
s

streetsofboston

03/04/2021, 6:40 PM
Why would a consumer try to unsafely downcast it back to a MutableStateFlow...? Isn't that asking for problems. Consumers should just consume it, not try to find a way to write/update it.
c

Charlie Christensen

03/04/2021, 6:40 PM
Yeah if you are responsible this isn't really an issue. This is just to guard against anyone who tries to do that
👍 1
a

Alex Prince

03/04/2021, 6:48 PM
yea exactly, it's just defensive programming, so that somebody down the line doesn't mess it up (probably you, if my experience is anything to go by)
2 Views