Skip to content

Instantly share code, notes, and snippets.

View mayojava's full-sized avatar

Mayowa Adegeye mayojava

View GitHub Profile
@mayojava
mayojava / user_orders.kt
Last active October 9, 2018 18:47
Shows a function that calls two asynchronous functions to login in a user and fetch list of orders
fun showUserOrders(username: String, password: String) {
val user = login(username, password)
val orders = fetchUserOrders(user.userId)
showUserOrders(orders)
}
fun login(username: String, password: String) { }
fun fetchUserOrders(userId: Long) { }
@mayojava
mayojava / user_orders_callback.kt
Created October 9, 2018 18:27
callback implementation to fetch user orders
fun showUserOrders(username: String, password: String) {
login(username, password) {
user -> fetchUserOrders(user.userId) {
orders -> showUserOrders(orders)
}
}
}
fun login(username: String, password: String, callback: (User) -> Unit)
@mayojava
mayojava / user_orders_rxjava.kt
Created October 9, 2018 18:45
RxJava implementation of show user orders
fun showUserOrders(username: String, password: String) {
login(username, password)
.flatMap { user -> fetchUserOrders(user.userId) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { showOrders(it) }
}
fun login(username: String, password: String): Single<User>
@mayojava
mayojava / user_orders_coroutines.kt
Created October 10, 2018 18:57
coroutine implementation of fetch user orders snippet
fun showUserOrders(username: String, password: String) = GlobalScope.launch(Dispatchers.Main) {
val user = withContext(Dispatchers.Default) { login(username, password) }
val orders = withContext(Dispatchers.Default) { fetchUserOrders(user.userId) }
showUserOrders(orders)
}
suspend fun login(username: String, password: String) { }
suspend fun fetchUserOrders(userId: Long) { }
fun main(args: Array<String>) = runBlocking {
repeat(100000) {
launch {
delay(100)
println("coroutine $it")
}
}
}
public fun withContext(
context: CoroutineContext,
block: suspend CorotuineScope.() -> T
): T
fun main (args: Array<String>) = runBlocking {
println("current thread: ${Thread.currentThread().name}")
//switch to default Dispatcher
val result = withContext(Dispatchers.Default) {
delay(500)
println("Thread: ${Thread.currentThread().name}")
100
}
fun CoroutineScope.async(
context: CoroutineContext = EmptyCorotuineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Deferred<T>
fun main(args: Array<String>) = runBlocking {
launch {
delay(1_000)
println("from launch coroutine body")
}
println("from runblocking")
}
//print
from runblocking
from launch coroutine body
fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val first = async { firstNumber() }
val second = async { secondNumber() }
val third = async { thirdNumber() }
val result = first.await() + second.await() + third.await()
}
println(time) //prints 7 seconds