aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/moe/yuuta/workmode/async/Async.kt
blob: 41542cd8a6ce2b759a9832b327954ce82bd3fe07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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?
)