Android : ViewModelStore
Ever wondered how ViewModel
survive during configuration changes in our Android apps? ๐ค
Let me introduce you to ViewModelStore
!
๐ What isViewModelStore
?
ViewModelStore
is a class that stores and manages ViewModel
instances. It's essential for keeping our ViewModel
s alive during configuration changes like screen rotations.
๐ Key Features:
Retain
ViewModel
s: KeepsViewModel
s during configuration changes.Efficient Resource Management: Automatically clears and notifies
ViewModel
s when they are no longer needed, preventing memory leaks.Easy Access: Retrieve
ViewModelStore
instances usingViewModelStoreOwner.getViewModelStore
.
๐ ๏ธ How Does it Work?
Storing ViewModels: Use the
put
method to add aViewModel
with a unique key. If aViewModel
with the same key exists, it's replaced and the old one is cleared.Retrieving ViewModels: Use the
get
method to fetch aViewModel
by its key.Listing Keys: Use the
keys
method to get a set of all keys.Clearing ViewModels: Call the
clear
method to notify and remove allViewModel
s.
Implementing ViewModel
in our app can significantly enhance its stability and performance. Give it a try and see the difference!
That's it for today. Happy Coding...
Subscribe to my newsletter
Read articles from Romman Sabbir directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Romman Sabbir
Romman Sabbir
Senior Android Engineer from Bangladesh. Love to contribute in Open-Source. Indie Music Producer.