Skip to content

Instantly share code, notes, and snippets.

@uddyami
Created April 24, 2019 04:08
Show Gist options
  • Select an option

  • Save uddyami/bdf64d7ef3f4d7016a45c99d02e45149 to your computer and use it in GitHub Desktop.

Select an option

Save uddyami/bdf64d7ef3f4d7016a45c99d02e45149 to your computer and use it in GitHub Desktop.

Revisions

  1. uddyami created this gist Apr 24, 2019.
    33 changes: 33 additions & 0 deletions Async.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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)
    }
    }
    }