In the project, I just joined I found strange `@Co...
# compose
d
In the project, I just joined I found strange
@Composable
usage
Copy code
class SomeViewModel(
    repository: SomeRepository,
) : ViewModel() {

    val something: State<String?>
        @Composable
        get() = repository.something.collectAsState()
}
what could be the implication of including
ViewModel
in composition?
j
I don't see any memory leaks here. Maybe some unnecessary subscriptions. Normally you want your Composable function outside of your ViewModel. I'd ditch the getter function and move the
collectAsState()
function to then UI.
d
For sure this needs to go to UI and
Flow
needs to be converted to
StatFlow
using
stateIn
.
But it's that circular reference as composable has reference to
ViewModel
and vice versa
s
Where does ViewModel have a reference to the composable?
d
isn’t the composable function in a body of the ViewModel?
s
ViewModel is allowed to have @Composable functions. Functions annotated like that aren’t always about emitting UI, in this case it’s returning a value, and that’s completely fine.
d
Do you see any advantage of using this instead of converting
Flow
to
StateFlow
?
s
I mean, I probably wouldn’t do it this way, but I don’t see something wrong with it. Could be missing something though 🤷‍♂️ Also this snippet makes it seem like the
something
is a StateFlow itself, since you’re using the
collectAsState
without any parameters, is that the case?
d
Because it’s
StateFlow
mind blown I just checked repository implementation.
s
Yeah, that’s probably a bit weird, to have a hot flow coming from the Repository, but ignoring that, then this looks fine I guess. The alternative is you do
.something
here and you simply move the
collectAsState()
in the UI, it’s pretty much the same thing I guess.