Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share same instance of ViewModel between Activities using Koin DI?

I am using Koin library in Kotlin for DI

Koin providing by viewmodel() for get instance of ViewModel by sharedViewModel() to get same instance in fragments.

How can I get same instance of the ViewModel in activities ? I didn't find any way to achieve this.

like image 415
Sahil Arora Avatar asked Jul 17 '19 14:07

Sahil Arora


2 Answers

you must use single{} instead of viewModel{} in module declaration.

single { SharedViewModel() }

And, you can use viewModel() in your views.

View1

private val viewModel: SharedViewModel by viewModel()

View2

private val viewModel: SharedViewModel by viewModel()

But you must load modules when view start by

loadKoinModules(module1)

The important point is that you must unload module in when destroy view.

unloadKoinModules(mainModule)

So, when unload modules your singleton ViewModel will be destroyed.

#EDIT

Now, you can use sharedViewModel declaration.

like image 120
Özer Özcan Avatar answered Oct 11 '22 15:10

Özer Özcan


After some research or discussion on architecture level and also report and issue github Koin,i found solution for this In this scenario,We should save that state/data into Repository which we need to share between multiple activities not in the viewModel and two or more different ViewModels can access same state/data that are saved in single instance of repository

see here

like image 5
Sahil Arora Avatar answered Oct 11 '22 14:10

Sahil Arora