cashapp / molecule

Build a StateFlow stream using Jetpack Compose
https://cashapp.github.io/molecule/docs/1.x/
Apache License 2.0
1.78k stars 76 forks source link

`CoroutineScope.launchMolecule` now returns a read-only state flow #432

Closed Goooler closed 2 months ago

Goooler commented 2 months ago

Avoid exposing mutable state flows in UI.


JakeWharton commented 2 months ago

Why? The return type is already StateFlow. If someone is doing an unsafe cast to the subtype that's a huge code smell and not really our problem.

Goooler commented 2 months ago

Just wanna the output StateFlow could be correctly consumed and avoid unsafe casts, to keep the same style in ViewModel like:

private val _state = MutableSharedFlow<State>(State.Initial)
val state: StateFlow<State> = _state.asStateFlow()
JakeWharton commented 2 months ago

I view this as an anti-pattern. In our internal codebase we ban such functions (and RxJava's hide before it) because you should not have to defend against someone doing unsafe casts. It's impossible to do comprehensively, and serves to only waste memory.

Kotlin's entire read-only collection API is implemented using the mutable types at runtime and we almost never are doing defensive copies and unmodifiable wrappers for those.

Goooler commented 2 months ago

Got it.