Search code examples
javaandroidtouchdb

How to share an instance of a TouchDB between an activity and fragment?


Currently I've got a TouchDB instance embedded in my main activity and have now hit a point where a separate fragment needs access to it and mearly passing data from the main activity to other activities isn't enough. Is there an recommended way of sharing the same db instance between activities/fragments? For instance in the image below which is similar to my app, fragment b requires access to the db, but on mobiles it'll be attached to Activity B and tablets Activity A (the main activity in my case).

enter image description here

Would extracting the db implementation out of my main activity and putting it in a singleton class be the recommended way? Or instantiate and destroy the db in each activity/fragment? If the later is the prefered approach is my understanding right in that, apart from the main activity it would be best to have the db implementation in the fragments rather than their related activity?


Solution

  • You should definitely extract your DB code from your view code. After that, you have a lot of options depending on the needs of your application.

    Patterns that might be useful depending on your needs:

    • Inversion of Control (IoC)
    • Dependency Injection
    • Factory
    • Singleton

    A side note on Singletons, which you mentioned as a possible solution. There is very little difference between a Singleton and a global static object. They share similar weaknesses - they introduce code dependencies, and code that uses them can be very difficult to write automated tests for. The main difference is that Singletons can control when the underlying object is first created - which probably has minimal impact on your application. (If your db code takes 10 seconds to load and you want to show a splash screen during the load, then the Singleton could be helpful.)