https://kotlinlang.org logo
#compose
Title
# compose
d

dawidhyzy

08/24/2022, 6:58 AM
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

jannis

08/24/2022, 5:17 PM
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

dawidhyzy

08/24/2022, 5:39 PM
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

Stylianos Gakis

08/24/2022, 6:53 PM
Where does ViewModel have a reference to the composable?
d

dawidhyzy

08/25/2022, 8:56 AM
isn’t the composable function in a body of the ViewModel?
s

Stylianos Gakis

08/25/2022, 9:20 AM
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

dawidhyzy

08/25/2022, 9:35 AM
Do you see any advantage of using this instead of converting
Flow
to
StateFlow
?
s

Stylianos Gakis

08/25/2022, 9:06 PM
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

dawidhyzy

08/26/2022, 5:50 AM
Because it’s
StateFlow
mind blown I just checked repository implementation.
s

Stylianos Gakis

08/26/2022, 6:34 AM
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.
3 Views