Multiple DataStore Instances when re-init FhirEngine during running application.
Describe the bug
When application tries to re-init FhirEngine (using FhirEngineProvider.init) during the same application process by first cleaning up (using FhirEngineProvider.cleanup) the app runs into the following error:-
There are multiple DataStores active for the same file: /data/user/0/[india.cardiac.heartcare.dev/files/datastore/FHIR_ENGINE_PREF_DATASTORE.preferences_pb](http://india.cardiac.heartcare.dev/files/datastore/FHIR_ENGINE_PREF_DATASTORE.preferences_pb). You should either maintain your DataStore as a singleton or confirm that there is no two DataStore's active on the same file (by confirming that the scope is cancelled)
Use-case of re-init - Availability of a fresh auth token!
Component Core library, SDC library, reference app, or SDC gallery app
To Reproduce Steps to reproduce the behavior:
- Go to '...'
- Click on '....'
- Scroll down to '....'
- See error
Expected behavior To be able to re-init FhirEngine whenever possible (as in the case of receiving a fresh auth token) including when the application is in a running state.
Screenshots If applicable, add screenshots to help explain your problem.
Smartphone (please complete the following information):
- Device: [e.g. Pixel4a emulator]
- Android version: [e.g. Settings -> About phone -> Android version]
- Build number: [e.g. Settings -> About phone -> Build number]
- Version [e.g. 22]
Additional context
FhirDataStore is not a true singleton. It's instantiated every time FhirEngineService is instantiated but not cleared when its cleared. Hence if an application initializes fhir engine multiple times, multiple FhirDataStore objects are created. And even though FhirServices object is nulled the FhirDataStore object remains dangling.
This violates DataStore policy of a singleton object since multiple objects are created within the FhirDataStore class.
Solution requires either or both of the following:-
- Move the Context.datastore outside of the FhirDataStore class
- Maintain a singleton of FhirDataStore like FhirServices instance and clear it in cleanup
Would you like to work on the issue? Please state if this issue should be assigned to you or who you think could help to solve this issue.