Search code examples
androidrobospiceretrofit

Robospice/ Retrofit background service accessing database


I've successfully created a Retrofit API Rest client making both GET & POST calls and also incorporated that into Robospice as a background service.

However, I want the Robospice service to connect to the database and asynchronously persist the retrieved objects from the GET call. Using the Retrofit Callback class seems the obvious way but connecting to the database requires Context and I"m concerned about leaking the Context.

so, what would be the best approach to get the Robospice SpiceService to persist data to the database both prior to and post a request being processed?


Solution

  • In the end, as I'm batching the various Rest API service calls to save radio (Reto Meier Dev Bytes: Efficient Data Transfers), I call the Rest API services (RetrofitSpiceServices) from within a controller Robospice SpiceService containing both the reference to the DatabaseHelper (requiring Context) and the respective Retrofit callbacks for the Rest services.

    This way, the controller service handles all the triggering (AlarmManager triggers the controller service) and persisting to DB and the Rest services can shut themselves down as normal without knowledge of context, database or suchlike.

    For @lion789:
    I have 4 models each with a corresponding API call to sync with the server (1 POST, 3 GET).
    To handle these sync calls, I have an IntentService that contains 4 SpiceManager attribute and 4 Retrofit Callback classes - one for each model/API call.
    The IntentService is passed an Enum indicating a sequence of APIs that should be called.
    The IntentService calls the appropriate SpiceManager which runs, then the Callback triggers the persistence and calls an IntentService method to trigger the next API call in the sequence.

    A lot of this is abstracted and interfaced as I use it for my Auth and Push Registration code so it's a bit of a nightmare to describe but it's been working pretty well thus far.