Search code examples
androidkotlinrepositorysingletonandroid-jetpack-datastore

Android: How to create only one instance of DatabaseRepository.kt and use it in different activities?


EDIT: I NEED TO PASS A CONTEXT AS A PARAMETER TO THE CLASS

(DataStore and repository is the same class, don't get confused)

I have two activities, A and B and one repository. Activity A opens activity B and activity B saves data in the repository(DataStore a part of android jetpack).

I am using LiveData in both the activities to observe data change in the DataStore.

After updating new values in the DataStore from activity B, the LiveData in the activity B gets new updated values as expected. But when i return back to activity A the LiveData gets the old the data (expecting the new updated data).

I realized that it is happening because i am creating two instances of the repository in both the activities.

How can i create only one instance of the repository class and use it in both the activities? If there's better way to do it then that solution is also welcomed.


Solution

  • Single instance based on static reference and passing Context as class parameter causes memory leak. In other hand you can use Application class to create one instance of required class

    class YourApp : Application(){
        val repository by lazy { YourRepository(this) }
    }
    

    and access it elsewhere with (context.applicationContext as YourApp).repository. And don't forget to declare android:name=... for application at manifest