'how can i share viewModel between Activities?

I'm learning Android ViewModel now. and I have MainActivity and RegisterActivity which can type name, age, and phone number in there. after typing that information in the RegisterActivity, I put that info into a ViewModel and click a button and finish the RegisterActivity. the thing is, I want to show the info in MainActivity. so how can I share the viewModel between the two activities? what a concept do I have to use?



Solution 1:[1]

You can't share a ViewModel across Activities. That's specifically one of the downsides of using multiple activities as per the Single Activity talk.

Solution 2:[2]

You can put the data you want to keep for the MainActivity into your Application class or use SharedPreferences.

Solution 3:[3]

ViewModel has application level lifecycle. If you use single viewmodel with two or more activities then after attaching with first activity when it get attached with other one. then there might be some problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ianhanniballake
Solution 2 Ridcully
Solution 3 Abhinav Raj