android - Is there a way to modularize code with the ability to run both asynchronously and on the main thread? -


suppose have object i've created. we'll call myobject.

i'd able save myobject database's corresponding table. don't want happen on activity's main thread. easy enough. created asynctask this.

however, application has intentservice used sync data between device's database , cloud database. i'd save myobjects have synced down cloud device's database here, too. however, not wish happen asynchronously in intentservice. want happen on intentservice's main thread.

the purpose, obviously, modularize code doesn't need duplicated.

how can modularize save code can called both asynchronously , synchronously?

i suspect create saveme() method inside myobject , declare static. intentservice, call saveme(). activity, launch asynctask passes in myobject , calls saveme(). sound right?

besides static sounds me, don't wish access instance variables?

i don't know how application designed in general, i'd go 1 of following patterns:

  • a subclass of runnable (or callable if need return values and/or exceptions) handles saving in general, suitable factory or constructor. can run these tasks directly or on background threads.
  • instances of objects have method save (this described), , these methods used synchronous or asynchronous code.
  • instances of databases / storage classes have method save myobject instances, assuming have common parent class can put code, , these methods used synchronous or asynchronous code.

the exact pattern depends on application you're working on imho.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -