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.

Source: Android Questions

LEAVE A COMMENT