package net.lacolaco.smileessence.util import android.os.AsyncTask import net.lacolaco.smileessence.logging.Logger abstract class BackgroundTask { private val task: InnerAsyncTask private var cbThen: ((Result) -> Unit)? = null private var cbProgress: ((Progress) -> Unit)? = null private var cbFail: ((Exception) -> Unit)? = null private var cbFinish: (() -> Unit)? = null private var exception: Exception? = null init { this.task = InnerAsyncTask() } fun onDone(cb: (Result) -> Unit): BackgroundTask { this.cbThen = cb return this } fun onProgress(cb: (Progress) -> Unit): BackgroundTask { this.cbProgress = cb return this } fun onFail(cb: (Exception) -> Unit): BackgroundTask { this.cbFail = cb return this } fun onFinish(cb: () -> Unit): BackgroundTask { this.cbFinish = cb return this } fun onDoneUI(cb: (Result) -> Unit): BackgroundTask { return onDone({ r -> UIHandler().post { cb(r) } }) } fun onProgressUI(cb: (Progress) -> Unit): BackgroundTask { return onProgress({ p -> UIHandler().post { cb(p) } }) } fun onFailUI(cb: (Exception) -> Unit): BackgroundTask { return onFail({ e -> UIHandler().post { cb(e) } }) } fun onFinishUI(cb: () -> Unit): BackgroundTask { return onFinish({ UIHandler().post(cb) }) } fun cancel(): Boolean { return task.cancel(true) } fun execute(): BackgroundTask { task.execute() return this } val immediately: Result get() { val result = task.get() return if (exception == null) { result } else { throw exception!! } } protected fun fail(ex: Exception) { exception = ex ex.printStackTrace() Logger.error(ex) if (!task.isCancelled && cbFail != null) { cbFail!!(ex) } } protected fun progress(value: Progress) { if (!task.isCancelled && exception == null && cbProgress != null) { cbProgress!!(value) } } protected abstract fun doInBackground(): Result private inner class InnerAsyncTask : AsyncTask() { override fun onPostExecute(result: Result?) { if (!isCancelled && exception == null && cbThen != null) { cbThen!!(result!!) } if (cbFinish != null) { cbFinish!!() } super.onPostExecute(result) } override fun doInBackground(vararg params: Void): Result? = try { this@BackgroundTask.doInBackground() } catch (ex: Exception) { fail(ex) null } } }