Skip to content
0:00 / 0:00

#viewmodel#androidjetpack#fragments

Shared ViewModel - Explained | Android Studio Tutorial

Stevdza-San

95K subscribers • 4 videos on Hallway

YouTube
  • Recommended by 1 person: 1 on Stack Overflow and its sister sites.

Intermediate. Assumes working knowledge.

47K views5 years ago1 recommendation

Mobile developmentSoftware designAndroid and Jetpack ComposeMobile app architectureDesign patterns

How to share a ViewModel instance between multiple Fragments by scoping it to the parent Activity.

🏆 My Online Courses ⭐Discount Coupon: LAUNCH-STEVDZA-SAN stevdza-san.com 🐱‍👤 Wanna become a member? Join! youtube.com/channel/UCYLAirIEMMXtWOECuZAtjqQ/join 📸 Instagram instagram.com/stevdza_san/ So far you might got used on having a single ViewModel instance per Fragment? So when you regularly instantiate one ViewModel in your Fragment, it's often scoped to a lifecycle of your Fragment, right? And by scoping that one ViewModel to a single Fragment you cannot share values between multiple Fragments. Which make sense. In order to Share values from the same ViewModel instance between multiple Fragments, you need to scope ViewModel to an Activity instead. Watch the video to learn more about it. ViewModel - Explained: youtu.be/orH4K6qBzvE ViewModel Factory: youtu.be/90ljEWTT5Xo 🕒 Timestamps: - Introduction - About the project - Create Shared ViewModel - Let's Start

Why it's here

1 person recommends this

What people say. Recommended as a solution for sharing data and state between different Fragments in an Android application.

Sam Chenon Stack Overflow • Recommends

On “Is there a way to pass a function reference between activities?”

2022 Update: My original approach has a drawback, in my demo if I press the home button to put the app into the background, it will crash with NotSerializableException . Actually there is another API just for listening changes from one Fragment in the other, that is FragmentResultListener , offical tutorial is here: link to this video. If FragmentResultListener cannot meet your need, Shared ViewModel is the final solution in there: link to this video. 1. You need to add id 'kotlin-parcelize' to your build.gradle (app), like this: plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-kapt' id 'kotlin-parcelize' //here } 2. Create a Class to wrap your Lambda function: @Parcelize…