diff options
Diffstat (limited to 'app/src/main/java/moe/yuuta/workmode/async/Async.kt')
-rw-r--r-- | app/src/main/java/moe/yuuta/workmode/async/Async.kt | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/app/src/main/java/moe/yuuta/workmode/async/Async.kt b/app/src/main/java/moe/yuuta/workmode/async/Async.kt new file mode 100644 index 0000000..41542cd --- /dev/null +++ b/app/src/main/java/moe/yuuta/workmode/async/Async.kt @@ -0,0 +1,47 @@ +package moe.yuuta.workmode.async + +import android.annotation.SuppressLint +import android.os.AsyncTask + +object Async { + fun <T> beginTask(runnable: Runnable<T>, callback: Callback<T>): Stoppable { + val task = @SuppressLint("StaticFieldLeak") + object : AsyncTask<Void, Void, TaskResult<T>>() { + override fun onPostExecute(result: TaskResult<T>) { + callback.onStop(result.successful, result.result, result.e) + } + + override fun doInBackground(vararg params: Void?): TaskResult<T> { + try { + return TaskResult(true, runnable.run(), null) + } catch (e: Throwable) { + return TaskResult(false, null, e) + } + } + + override fun onPreExecute() { + callback.onStart() + } + } + val stoppable = object : Stoppable { + override fun stop() { + if (!isStopped()) task.cancel(true) + } + + override fun isStopped(): Boolean = task.isCancelled + } + task.execute() + return stoppable + } +} + +@FunctionalInterface +interface Runnable<T> { + fun run(): T? +} + +data class TaskResult<T>( + val successful: Boolean, + val result: T?, + val e: Throwable? +)
\ No newline at end of file |