
Article about this library: Every Composable deserves a ViewModel
Resaca 🍹
The right scope for objects and View Models in Android Compose.
Resaca provides a simple way to keep a Jetpack ViewModel (or any other object) in memory during the lifecycle of a @Composable function and automatically
clean it up when not needed anymore. This means, it retains your object or ViewModel across recompositions, during configuration changes, and also when the
container Fragment or Compose Navigation destination goes into the backstack.
With Resaca you can create fine grained ViewModels for fine grained Composables and finally have reusable components across screens.
Why
Compose allows the creation of fine-grained UI components that can be easily reused like Lego blocks 🧱. Well architected Android apps isolate functionality in
small business logic components (like use cases, interactors, repositories, etc.) that are also reusable like Lego blocks 🧱.
Screens are built using Compose components together with business logic components, and the standard tool to connect these two types of components is
a Jetpack ViewModel. Unfortunately, ViewModels can only be scoped to a whole screen (or
larger scope), but not to smaller Compose components on the screen.
In practice, this means that we are gluing UI Lego blocks with business logic Lego blocks using a big glue class for the whole screen, the ViewModel 🗜.
Until now...
Installation
Just include the library (less than 5Kb):
Kotlin (KTS)
dependencies {
implementation("io.github.sebaslogen:resaca:X.X.X")
}
Groovy
dependencies {
// The latest version of the lib is available in the badget at the top from Maven Central, replace X.X.X with that version
implementation 'io.github.sebaslogen:resaca:X.X.X'
}
Usage
Inside your @Composable function create and retrieve an object using rememberScoped to remember any type of object (except ViewModels). For ViewModels use
viewModelScoped. That's all 🪄✨
Examples:
Scope an object to a Composable
@Composable
fun DemoScopedObject() {
val myRepository: MyRepository = rememberScoped { MyRepository() }
DemoComposable(inputObject = myRepository)
}
Scope a ViewModel to a Composable
@Composable
fun DemoScopedViewModel() {
val myScopedVM: MyViewModel = viewModelScoped()
DemoComposable(inputObject = myScopedVM)
}
Scope a ViewModel with a dependency to a Composable
@Composable
fun DemoScopedViewModelWithDependency() {
val myScopedVM: MyViewModelWithDependencies = viewModelScoped { MyViewModelWithDependencies(myDependency) }
DemoComposable(inputObject = myScopedVM)
}
Scope a ViewModel with a key to a Composable
@Composable
fun DemoViewModelWithKey() {
val scopedVMWithFirstKey: MyViewModel = viewModelScoped("myFirstKey") { MyViewModel("myFirstKey") }
val scopedVMWithSecondKey: MyViewModel = viewModelScoped("mySecondKey") { MyViewModel() }
DemoComposable(inputObject = scopedVMWithFirstKey)
DemoComposable(inputObject = scopedVMWithSecondKey)
}
Scope a ViewModel with a dependency injected with Koin to a Composable
@Composable
fun DemoKoinInjectedViewModelWithDependency() {
val myInjectedScopedVM: MyViewModelWithDependencies = viewModelScoped() { getKoin().get { parametersOf(myConstructorDependency) } }
DemoComposable(inputObject = myInjectedScopedVM)
}
Scope a ViewModel with a dependency injected with Metro to a Composable
@Composable
fun DemoMetroInjectedViewModelScoped() {
val myInjectedScopedVM: MyViewModel = metroViewModelScoped(factory = myMetroViewModelFactory)
DemoComposable(inputObject = myInjectedScopedVM)
}
Scope a ViewModel with a clear delay to a Composable
@Composable
fun DemoScopedViewModelWithClearDelay() {
val myScopedVM: MyViewModel = viewModelScoped(clearDelay = 5.seconds)
DemoComposable(inputObject = myScopedVM)
}
Scope an object with a clear delay to a Composable
@Composable
fun DemoScopedObjectWithClearDelay() {
val myRepository: MyRepository = rememberScoped(clearDelay = 5.seconds) { MyRepository() }
DemoComposable(inputObject = myRepository)
}
Use a different ViewModel for each item in a LazyColumn and scope them to the Composable that contains the LazyColumn
@Composable
fun DemoManyViewModelsScopedOutsideTheLazyColumn(listItems: List<Int> = (1..1000).toList()) {
val keys = rememberKeysInScope(inputListOfKeys = listItems)
LazyColumn() {
items(items = listItems, key = { it }) { item ->
myScopedVM: MyViewModel = viewModelScoped(key = item, keyInScopeResolver = keys)
DemoComposable(inputObject = myScopedVM)
}
}
}
Once you use the rememberScoped or viewModelScoped functions, the same object will be restored as long as the Composable is part of the composition, even if
it temporarily leaves composition on configuration change (e.g. screen rotation, change to dark mode, etc.) or while being in the backstack.
For ViewModels, in addition to being forgotten when they're really not needed anymore, their coroutineScope will also be automatically canceled because
ViewModel's onCleared method will be automatically called.
💡 Optional key: a key can be provided to the call, rememberScoped(key) { ... } or viewModelScoped(key) { ... }. This makes possible to forget an old
object when there is new input data during a recomposition (e.g. a new input id for your ViewModel).
💡 Optional clearDelay: a clearDelay can be provided to delay the disposal of the scoped object after the Composable is removed from composition.
This is useful when a Composable might briefly leave composition and return (e.g. quick navigation back and forth), and you want to avoid recreating expensive objects.
Usage: rememberScoped(clearDelay = 5.seconds) { ... } or viewModelScoped(clearDelay = 5.seconds).
If the Composable returns to composition before the delay expires, the disposal is cancelled and the same object is reused.
⚠️ Note that ViewModels remembered with viewModelScoped should not be created using any of the Compose viewModel() or ViewModelProviders factories,
otherwise they will be retained in the scope of the screen regardless of . Also, if a ViewModel is remembered with , instead of , then its
clean-up method won't be called, so it's always better to use for ViewModels.
Sample use cases
Here are some sample use cases reported by the users of this library:
Demo app
Demo app documentation can be found here.
| Before | After backstack navigation & configuration change |
|---|
 |  |
Multiplatform support
Resaca works in Kotlin Multiplaform and also in Compose Multiplatform for Android, iOS, Desktop-JVM and Web targets:
Compose Multiplatform
Since version 4.0, Resaca supports Compose Multiplatform for Android, iOS, Desktop-JVM and Web targets.
To see an example of usage and configuration check the in the module.
Dependency injection support
This library does not influence how your app provides or creates objects so it's dependency injection strategy and framework agnostic.
Nevertheless, this library supports three of the main dependency injection frameworks:
Hilt 🗡️
Hilt details
HILT (Dagger) support is available in a small extension of this library: resaca-hilt.
Documentation and installation instructions are available here.
Koin 🪙
Metro 🚇
Scoping in a LazyColumn, LazyRow, etc
This is handy for the typical case where you have a lazy list of items and you want to have a separate ViewModel for each item in the list, using the viewModelScoped function.
General considerations for State Hoisting
When a Composable is used more than once in the same screen with the same input, then the ViewModel (or business logic object) should be provided only once
with viewModelScoped at a higher level in the composition tree using Compose's State Hoisting.
Why not use remember?
Lifecycle explained