I'm learning how to use Android Room from google-developer-training, where I found example of repository class
. I try to simplify my SportRepository
class. I wonder how to avoid repetition of inner class ...AsyncTask
in my code. Here is very sample example:
@Singleton
class SportRepository {
val LOG_TAG = SportRepository::class.java.name
@Inject
lateinit var sportDAO: SportDAO
var list: LiveData<List<Sport>>
init {
App.app().appComponent()?.inject(this)
list = sportDAO.getAll()
}
fun insert(sport: Sport) {
insertAsyncTask().execute(sport)
}
fun update(sport: Sport){
updateAsyncTask().execute(sport)
}
fun delete(sport: Sport) {
deleteAsyncTask().execute(sport)
}
@SuppressLint("StaticFieldLeak")
private inner class insertAsyncTask() : AsyncTask<Sport, Void, Void>() {
override fun doInBackground(vararg p0: Sport): Void? {
sportDAO.insert(p0.get(0))
return null
}
}
@SuppressLint("StaticFieldLeak")
private inner class updateAsyncTask() : AsyncTask<Sport, Void, Void>() {
override fun doInBackground(vararg p0: Sport): Void? {
sportDAO.update(p0[0])
return null
}
}
@SuppressLint("StaticFieldLeak")
private inner class deleteAsyncTask() : AsyncTask<Sport, Void, Void>() {
override fun doInBackground(vararg p0: Sport): Void? {
sportDAO.delete(p0[0])
return null
}
}
}
The AsyncTask
classes differ only in name and in kind of method invoke from sportDAO class.
Is there any way to avoid creating many almost the same AsyncTask
classes?
I've not found any example how to simplify that.