aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/util/UIHelpers.kt
blob: 898a922116d9bb35cf9e16ae68750c0812161103 (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
package net.lacolaco.smileessence.util

import android.util.Log
import kotlinx.coroutines.*
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
}

fun launchUi(block: suspend CoroutineScope.() -> Unit) =
        GlobalScope.launch(Dispatchers.Main, block = block)

fun <T> bg(block: suspend CoroutineScope.() -> T) =
        GlobalScope.async(Dispatchers.Default + exceptionHandler, block = block)

fun launchBg(block: suspend CoroutineScope.() -> Unit) =
        GlobalScope.launch(Dispatchers.Default + exceptionHandler, block = 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)