Skip to content

Instantly share code, notes, and snippets.

Avatar
☯️

Glenn pencelab

☯️
View GitHub Profile
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...")
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)
}
@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-main-function-getting-random-number-using-object.kt
fun main() {
log("Start")
val myObject = MyObject()
runBlocking {
log("RunBlocking start")
val def = myObject.sumRandomNumbersAsync()
View kotlin-coroutines-stories-09-operator-class-no-operations.kt
class Operator: CoroutineScope {
companion object {
const val OPERATION_IS_EVEN = "Operation [Is Even]"
const val OPERATION_AVERAGE = "Operation [Average]"
const val OPERATION_SQUARE = "Operation [Square]"
}
private val job = SupervisorJob()
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
You can’t perform that action at this time.