Created
September 11, 2019 20:47
-
-
Save Megamiun/33334e1ce7dd8c49ab3928dff49f1511 to your computer and use it in GitHub Desktop.
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
package br.com.gabryel.playground.rx | |
import io.reactivex.Observable | |
import io.reactivex.rxkotlin.toObservable | |
import io.reactivex.rxkotlin.zipWith | |
import java.time.LocalTime | |
import java.util.concurrent.TimeUnit | |
import kotlin.math.pow | |
fun main() { | |
val list = listOf("a", "b", "c") | |
val sleepMilli = 1000L | |
rxWay(list, sleepMilli) | |
listWay(list, sleepMilli) | |
sequenceWay(list, sleepMilli) | |
} | |
private fun rxWay(list: List<String>, sleepMilli: Long) { | |
val time = LocalTime.now() | |
printValues("RX") { | |
Observable | |
.interval(sleepMilli, TimeUnit.MILLISECONDS) | |
.zipWith(list.toObservable()) | |
.doOnNext { event -> | |
println("Requesting $event: ${getTimeDifference(time)}") | |
}.doOnNext { event -> | |
println("Saving DB $event: ${getTimeDifference(time)}") | |
Thread.sleep(600) | |
}.doOnComplete { | |
println("Finishing: ${getTimeDifference(time)}") | |
}.subscribe() | |
Thread.sleep(10000) | |
} | |
} | |
private fun listWay(list: List<String>, sleepMilli: Long) { | |
val time = LocalTime.now() | |
printValues("LIST") { | |
list.map { event -> | |
println("Requesting $event: ${getTimeDifference(time)}") | |
Thread.sleep(sleepMilli) | |
}.forEach { event -> | |
println("Saving DB $event: ${getTimeDifference(time)}") | |
Thread.sleep(600) | |
} | |
println("Finishing: ${getTimeDifference(time)}") | |
} | |
} | |
private fun sequenceWay(list: List<String>, sleepMilli: Long) { | |
val time = LocalTime.now() | |
printValues("SEQUENCE") { | |
list.asSequence().map { event -> | |
println("Requesting $event: ${getTimeDifference(time)}") | |
Thread.sleep(sleepMilli) | |
}.forEach { event -> | |
println("Saving DB $event: ${getTimeDifference(time)}") | |
Thread.sleep(600) | |
} | |
println("Finishing: ${getTimeDifference(time)}") | |
} | |
} | |
private fun printValues(type: String, block: () -> Unit) { | |
println() | |
println("---- $type ----") | |
block() | |
println("---- $type ----") | |
println() | |
} | |
private fun getTimeDifference(time: LocalTime) = | |
(LocalTime.now().toNanoOfDay() - time.toNanoOfDay()) / 10.toDouble().pow(6.toDouble()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment