https://kotlinlang.org logo
#android
Title
# android
g

Gaurav K Tyagi 1

06/05/2020, 11:29 AM
Hi @all How can we share viewmodel between diffetent activities ?
k

Karol Ksionek

06/05/2020, 11:38 AM
why do you want to do that?
g

Gaurav K Tyagi 1

06/05/2020, 11:39 AM
I want to update my parent activity. I mean the activity from where i launch new activity
k

Karol Ksionek

06/05/2020, 11:40 AM
shouldn’t you use startActivityForResult?
g

Gaurav K Tyagi 1

06/05/2020, 11:41 AM
Yes I can . But is it possible with VM?
k

Karol Ksionek

06/05/2020, 11:43 AM
Yes, you will have 2 separate view models. Activity 1 starts the second activity for result. When the activity 2 is done, it sets the result. Then activity 1 gets the result and passes it to the view model
g

Gaurav K Tyagi 1

06/05/2020, 11:46 AM
Ok. So in short we can not share view model between activities like we can share between fragments. We will have to achive it using start activity for result only.
👍 1
i

Ivann Ruiz

06/05/2020, 12:01 PM
You can share the viewmodel but it's not good practice. The lifecycle of the 2 activities wouldn't play well with a single viewmodel. The better option would be to startActivityForResult imo
o

OG

06/05/2020, 4:11 PM
I mean.. you can technically do anything... Crazy stuff like pass the ViewModel from activity1 to activity 2.... Should you do that .. like ever.... Is another question. Lol Like the gentlemen above suggested, startActivityForResult would be a better option
g

Gaurav K Tyagi 1

06/05/2020, 5:15 PM
Nice. Thanks to all of you 😊