Closed brentwatson closed 7 months ago
Yes, I believe your assessment is correct. Internally we have a custom base class we use for our viewmodels and we mark that with @Stable. However, while that should generally work, there is nothing stopping somebody from any public properties to their viewmodel and incorrectly using them from compose UI. For that reason I don't think it would be right to add the @Stable annotation within this library.
I think updating the docs to suggest the best practice would be best. I think your second two options are both good. If people happen to have/want a custom base class they can put the annotation there, otherwise using compose_compiler_config.conf is a fine option.
Internally we have strong guidelines enforcing that no properties besides state flow are accessed off the viewmodel during composition to prevent mistakes and guarantee stability. We could possibly provide a util function to perform that validation on the viewmodel, but it would be up to users to set up a test to call that function. I'm thinking about something that takes the viewmodel as a parameter and uses reflection to enforce that all properties are private/protected (perhaps unless the return type has a @StableMarker annotation), and all public/internal functions only return Unit
.
The viewmodel already does some debug checks around proper state immutability, but I don't think it would be proper to add a stability check like this retroactively, so it would need to be opt in.
If you want to put up a PR to add those details to the docs, and/or work on a stability validation util, I'd be happy to review
Appreciate the info @elihart! For stability validation I ended up first making a PSI check that happened at compile time (hooked into Anvil) and then ended up converting that into a custom detekt rule. Hopefully these can be of use to someone...
/**
* Can be suppressed with `@Suppress("UnstableViewModel")`
*/
private fun ensureCanBeMarkedStable(clazz: Psi) {
val suppressed = clazz.annotations.any {
it.fqName == Suppress::class.fqName && it.arguments.any { arg -> arg.value<String>() == "UnstableViewModel" }
}
if (!suppressed) {
val publicProperties = clazz.properties
.filter { it.visibility() !in listOf(PRIVATE, PROTECTED) }
val functionsWithNonUnitReturn = clazz.functions
.filter { it.visibility() !in listOf(PRIVATE, PROTECTED) && it.returnTypeOrNull() != null }
if (publicProperties.isNotEmpty() || functionsWithNonUnitReturn.isNotEmpty()) {
val propErrors = publicProperties.joinToString(",") { "${it.name} should be private" }
val funcErrors = functionsWithNonUnitReturn.joinToString(",") { "${it.name} should return Unit" }
error("UnstableViewModel: ${clazz.fqName} would be considered an unstable type by the compose compiler: $propErrors $funcErrors")
}
}
}
@RequiresTypeResolution
class UnstableMavericksViewModel : Rule() {
override val issue = Issue(
javaClass.simpleName,
Severity.Defect,
"MavericksViewModel classes should not have public/internal properties, and all public/internal functions should return Unit " +
"so that they are considered stable types by the compose compiler when used as params in compose functions",
Debt.TWENTY_MINS
)
override fun visitClass(klass: KtClass) {
if (klass.getSuperNames().contains("MavericksViewModel")) {
klass.getProperties()
.filter { it.isPublic || it.isInternal() }
.forEach { property ->
report(
CodeSmell(
issue = issue,
entity = Entity.from(klass),
message = "${property.name ?: "Properties"} should be private, " +
"ViewModel would be considered an unstable type by the compose compiler"
)
)
}
klass.declarations
.filterIsInstance<KtNamedFunction>()
.filter { it.isPublic || it.isInternal() }
.filter {
bindingContext[BindingContext.FUNCTION, it]?.returnType?.isUnit() != true
}
.forEach {function ->
report(
CodeSmell(
issue = issue,
entity = Entity.from(klass),
message = "${function.name ?: "Functions"} should return Unit, " +
"ViewModel would be considered an unstable type by the compose compiler"
)
)
}
}
}
}
They would both need additional logic to be added anywhere official, as they assume that all VMs are used in Composables which isn't necessarily true.
Thanks for sharing this, that's great! I hope others can reuse this and build on it. I'll close for now assuming there's no more to discuss
This is not a Mavericks issue, but maybe it's something Mavericks can improve on over regular Jetpack ViewModels.
Since VMs are parameters to Composable functions:
... if the ViewModel is complex and is marked as
Unstable
by the compose compiler, the Composable function also becomes unstable and will recompose more than expected. This is often triggered by parameters accepted by the ViewModel and can go unnoticed.Here is a simple reproduction example using Mavericks Compose Sample App: https://github.com/airbnb/mavericks/compare/main...brentwatson:mavericks:vm-stability-repro
Compose Compiler report:
If Mavericks is used as documented a ViewModel will never actually be an unstable type, so I believe Mavericks could provide a solution to this issue over standard Jetpack ViewModels.
Happy to work on a PR with a solution, but looking for input on what the Maverick teams thinks is the best solution to this problem:
mavericksViewModel()
(and similar) functions could return a@Stable
MavericksViewModel
@Stable
com.airbnb.mvrx.MavericksViewModel
to compose_compiler_config.confMore details/additional reading here: https://multithreaded.stitchfix.com/blog/2022/08/05/jetpack-compose-recomposition/