Android : ViewModelStore

Romman SabbirRomman Sabbir
1 min read

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 ViewModels alive during configuration changes like screen rotations.

๐Ÿ“Œ Key Features:

  • RetainViewModels: Keeps ViewModels during configuration changes.

  • Efficient Resource Management: Automatically clears and notifies ViewModels when they are no longer needed, preventing memory leaks.

  • Easy Access: Retrieve ViewModelStore instances using ViewModelStoreOwner.getViewModelStore.

๐Ÿ› ๏ธ How Does it Work?

  1. Storing ViewModels: Use the put method to add a ViewModel with a unique key. If a ViewModel with the same key exists, it's replaced and the old one is cleared.

  2. Retrieving ViewModels: Use the get method to fetch a ViewModel by its key.

  3. Listing Keys: Use the keys method to get a set of all keys.

  4. Clearing ViewModels: Call the clear method to notify and remove all ViewModels.

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...

0
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.