Skip to content

Instantly share code, notes, and snippets.

Avatar
☯️

Glenn pencelab

☯️
View GitHub Profile
View kotlin-coroutines-stories-09-load-items-function-regular.kt
fun loadItems() {
showLoadingView()
val data = requestData()
hideLoadingView()
appendItemsToListView(data)
}
View kotlin-coroutines-stories-09-load-items-function-with-context-verbose.kt
suspend fun loadItems() {
withContext(Dispatchers.Main) {
showLoadingView()
}
withContext(Dispatchers.IO) {
val data = requestData()
}
withContext(Dispatchers.Main) {
hideLoadingView()
appendItemsToListView(data)
View kotlin-coroutines-stories-09-load-items-function-with-context-dispatchers-io.kt
suspend fun loadItems() = withContext(Dispatchers.IO) {
withContext(Dispatchers.Main) {
showLoadingView()
}
val data = requestData()
withContext(Dispatchers.Main) {
hideLoadingView()
appendItemsToListView(data)
}
}
View kotlin-coroutines-stories-09-load-items-function-with-context-dispatchers-main.kt
suspend fun loadItems() = withContext(Dispatchers.Main) {
showLoadingView()
val data = withContext(Dispatchers.IO) {
requestData()
}
hideLoadingView()
appendItemsToListView(data)
}
View kotlin-coroutines-stories-09-load-items-function-with-context-implicit.kt
suspend fun loadItems() {
showLoadingView()
val data = withContext(Dispatchers.IO) {
requestData()
}
hideLoadingView()
appendItemsToListView(data)
}
View kotlin-coroutines-stories-09-main-function-getting-random-number-using-object.kt
fun main() {
log("Start")
val myObject = MyObject()
runBlocking {
log("RunBlocking start")
val def = myObject.sumRandomNumbersAsync()
@pencelab
pencelab / kotlin-coroutines-stories-09-random-number-suspend-function.kt
Last active Oct 29, 2019
Suspend functions to produce a random number.
View kotlin-coroutines-stories-09-random-number-suspend-function.kt
private suspend fun myRandomNumber(): Int = withContext(Dispatchers.Default) {
log("Retrieving random number...")
delay(2000) //Simulating a heavy computation
val random = (1..100).random()
log("Random Number = $random")
random
}
View kotlin-coroutines-stories-09-runblocking-two-operations.kt
runBlocking {
val defIsEven = operator.sumIsEvenAsync()
val defAverage = operator.sumAverageAsync()
launch {
try {
log("Operation [Is Even] Result = ${defIsEven.await()}")
} catch (e: Exception) {
log("Operation [Is Even] Caught: [ $e ]")
} finally {
View kotlin-coroutines-stories-09-random-number-suspend-functions.kt
private suspend fun myRandomNumberSuccess(operation: String): Int = withContext(Dispatchers.Default) {
log("$operation Retrieving random number...")
delay(2000) //Simulating a heavy computation
val random = (1..100).random()
log("$operation Random Number = $random")
random
}
private suspend fun myRandomNumberFail(operation: String): Int = withContext(Dispatchers.Default) {
log("$operation Retrieving random number...")
You can’t perform that action at this time.