This repository has been archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Async.kt
211 lines (191 loc) · 6.61 KB
/
Async.kt
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.jetbrains.anko
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Handler
import android.os.Looper
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* Execute [f] on the application UI thread.
*/
fun Context.runOnUiThread(f: Context.() -> Unit) {
if (ContextHelper.mainThread == Thread.currentThread()) f() else ContextHelper.handler.post { f() }
}
/**
* Execute [f] on the application UI thread.
*/
inline fun Fragment.runOnUiThread(crossinline f: () -> Unit) {
activity?.runOnUiThread { f() }
}
class AnkoAsyncContext<T>(val weakRef: WeakReference<T>)
/**
* Execute [f] on the application UI thread.
* If the [doAsync] receiver still exists (was not collected by GC),
* [f] gets it as a parameter ([f] gets null if the receiver does not exist anymore).
*/
fun <T> AnkoAsyncContext<T>.onComplete(f: (T?) -> Unit) {
val ref = weakRef.get()
if (ContextHelper.mainThread == Thread.currentThread()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
}
/**
* Execute [f] on the application UI thread.
* [doAsync] receiver will be passed to [f].
* If the receiver does not exist anymore (it was collected by GC), [f] will not be executed.
*/
fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit): Boolean {
val ref = weakRef.get() ?: return false
if (ContextHelper.mainThread == Thread.currentThread()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
return true
}
/**
* Execute [f] on the application UI thread if the underlying [Activity] still exists and is not finished.
* The receiver [Activity] will be passed to [f].
* If it is not exist anymore or if it was finished, [f] will not be called.
*/
fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
fun <T: Activity> AnkoAsyncContext<T>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
@JvmName("activityContextUiThread")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
@JvmName("activityContextUiThreadWithContext")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { f(fragment) }
return true
}
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { activity.f(fragment) }
return true
}
private val crashLogger = { throwable : Throwable -> throwable.printStackTrace() }
/**
* Execute [task] asynchronously.
*
* @param exceptionHandler optional exception handler.
* If defined, any exceptions thrown inside [task] will be passed to it. If not, exceptions will be ignored.
* @param task the code to execute asynchronously.
*/
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
return@submit try {
context.task()
} catch (thr: Throwable) {
val result = exceptionHandler?.invoke(thr)
if (result != null) {
result
} else {
Unit
}
}
}
}
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<Unit> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<R> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
internal object BackgroundExecutor {
var executor: ExecutorService =
Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors())
fun <T> submit(task: () -> T): Future<T> {
return executor.submit(task)
}
}
private object ContextHelper {
val handler = Handler(Looper.getMainLooper())
val mainThread: Thread = Looper.getMainLooper().thread
}