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
|
package net.lacolaco.smileessence.util
import android.util.Log
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.UI
import net.lacolaco.smileessence.World
import java.lang.ref.WeakReference
private val exceptionHandler = CoroutineExceptionHandler { c, throwable ->
val tag = "CoroutineContext:$c"
Log.e(tag, "Uncaught exception ${throwable::class}; re-throwing...")
throw throwable
}
val uiContext = UI + exceptionHandler
val bgContext = CommonPool + exceptionHandler
fun launchUi(block: suspend CoroutineScope.() -> Unit) {
launch(uiContext, CoroutineStart.DEFAULT, null, null, block)
}
fun <T> bg(block: suspend CoroutineScope.() -> T) =
async(bgContext, CoroutineStart.DEFAULT, null, null, block)
fun launchBg(block: suspend CoroutineScope.() -> Unit) =
launch(bgContext, CoroutineStart.DEFAULT, null, null, block)
fun World.getMainActivityOrCancel() =
getMainActivity() ?: throw CancellationException("MainActivity is gone")
class CancellableReference<out T> internal constructor(obj: T) {
private val ref = WeakReference(obj)
fun get() = ref.get() ?: throw CancellationException("Object is gone")
}
fun <T> ref(obj: T) = CancellableReference(obj)
|