Shared ViewModel - Explained | Android Studio Tutorial

Stevdza-San · 47K views · 2021 · 11:40

Open on YouTube

Software architecture & designSoftware (other)tutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about passing data between Fragments or using one ViewModel across several Fragments.

Recommended by 1 people across 1 different months, 2021 to 2023.

What it is

A short Android Studio tutorial by Stevdza-San on sharing one ViewModel instance between multiple Fragments by scoping it to the Activity instead of each Fragment. It walks through creating a shared ViewModel and using it in a sample project.

What people said

Recommends Alvaro Ramirez Crisostomo · 2023-01 · Stack Overflow · on “How can I save the entered values in an editText until the app is completely closed and destroyed?”

@RushiMayur No, the saveData() and getData() should be inside of the ViewModel. The dataClass object must be in other file and alone. Create the shared viewModel with this video [this video] . And the saveDatainViewModel should be in the Estimator fragment, out of onCreateView but inside of the EstimatorFragment class. So then inside of the onViewCreated(you have to override this method) you call the function obtainData()

Cites Sam Chen · 2021-03 · Stack Overflow · 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] . If FragmentResultListener cannot meet your need, Shared ViewModel is the final solution in there: [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 class Listener(val

Cites Rahul · 2021-12 · Stack Overflow · on “Android: One ViewModel for multiple Fragments possible?”

You can go through with this link Shareable ViewModel [this video] This is pretty much easy with Kotlin by using extention function, But In Java, we need to create a function for creating ViewModel and handle their scope according to the lifecycle of activity/fragment.