I'm making an Android app that follows the MVVM pattern using Room and LiveData, but I need to return the ID of the last insertion in one table because is used to add values in other table where the ID is the foreign key, I know that I can achive this returning it from the DAO:
@Dao
interface TratamientoDao {
@Insert
fun insert(tratamiento : Tratamiento): Long
}
But the problem is that I need to return a value from the AsyncTask that inserts the new entry,I tried the approach explained in this question: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
But In my case the method processFinish is never called.
This is my code:
interface AsyncValue{
fun processFinish(lastID: Long?) : Long?
}
class TratamientoRepository (application: Application): AsyncValue {
val tratamientoDao : TratamientoDao
init{
val database = MMRDataBase.getInstance(application)
tratamientoDao = database.tratamientoDao()
}
fun insert(tratamiento: Tratamiento) : Long? {
InsertTratamientoAsyncTask(tratamientoDao).execute(tratamiento)
return 45
}
override fun processFinish(lastID: Long?): Long? {
Log.d("ValorIngresado:", lastID.toString())
return lastID
}
private class InsertTratamientoAsyncTask constructor(private val tratamientoDao: TratamientoDao) : AsyncTask<Tratamiento, Void, Long>(){
var completionCode : AsyncValue? = null
override fun doInBackground(vararg params: Tratamiento): Long?{
return tratamientoDao.insert(params[0])
}
override fun onPostExecute(result: Long?) {
completionCode?.processFinish(result)
//Log.i("TAMANO", result.toString())
}
}
}
So, How can I return a value from an AsyncTask in Kotlin?