Retained Instance
A lightweight library built on top of Android Architecture Component ViewModel to simplify how UI Controllers (e.g., Activity
, Fragment
& NavBackStackEntry
) retain instances on Android.
- Eliminate
ViewModel
inheritance. - Eliminate
ViewModelProvider.Factory
need. - Easy access to
ViewModel
scoped properties:CoroutineScope
(viewModelScope
),SavedStateHandle
, and many others. - Enable composition: callbacks can be listened with
OnClearedListener
.
Motivation: Retained was originally created to share a ViewModel
in Kotlin Multiplatform projects between Android & iOS with ease.
Download
(Please replace {Tag}
with the latest version numbers)
Usage
The following sections demonstrate how to retain instances in activities and fragments. For simplicity, all examples will retain the following class:
Use Retained in Activities and Fragments
Use Retained in Compose
Advanced usage
Custom parameters from Jetpack's ViewModel
When retaining an instance, you have access to a RetainedEntry
which contains all parameters you might need.
The entry exposes a SavedStateHandle
that can be used to work with the saved state, just like in a regular Android ViewModel
.
It also exposes a CoroutineScope
that works just like viewModelScope
from the Android ViewModel
.
For more details, see RetainedEntry
.
Listening onCleared
calls
When retaining an instance, you can use the RetainedEntry
to be notified when a retained instance is cleared (ViewModel.onCleared
).
As a convenience, if the retained instance implements the OnClearedListener
interface, it will be automatically added to onClearedListeners
and notified.
View support (Experimental)
Besides Activities and Fragments, it's also possible to retain instances in a view. There are a couple of extra modules for that:
The retained-view
module exposes retainInActivity
and retain
, which will scope the instance to the parent being it an activity or a fragment. The retained-view-navigation
module exposes retainInNavGraph
to retain instances scoped to the NavGraph
.
License
Copyright 2019 Marcello Galhardo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.