forked from metalabdesign/AsyncAwait
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement async/await for Android using Kotlin Coroutines
- Loading branch information
Showing
4 changed files
with
139 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package coroutineandroid | ||
|
||
import android.os.Handler | ||
import android.os.Looper | ||
import kotlin.coroutines.Continuation | ||
|
||
fun asyncUi(coroutine c: AsyncController.() -> Continuation<Unit>): AsyncController { | ||
val controller = AsyncController() | ||
// TODO If not in UI thread - force run resume() in UI thread | ||
controller.c().resume(Unit) | ||
return controller | ||
} | ||
|
||
class AsyncController { | ||
private var errorHandler: ErrorHandler? = null | ||
private val uiHandler = Handler(Looper.getMainLooper()) | ||
|
||
suspend fun <V> await(f: () -> V, machine: Continuation<V>) { | ||
Thread { | ||
try { | ||
val value = f() | ||
uiHandler.post { | ||
machine.resume(value) | ||
} | ||
} catch (e: Exception) { | ||
uiHandler.post { | ||
errorHandler?.invoke(e) ?: machine.resumeWithException(e) | ||
} | ||
} | ||
|
||
}.start() | ||
|
||
} | ||
|
||
fun onError(errorHandler: ErrorHandler) { | ||
this.errorHandler = errorHandler | ||
} | ||
} | ||
|
||
typealias ErrorHandler = (Exception) -> Unit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters