Skip to content

Instantly share code, notes, and snippets.

View jaozinfs's full-sized avatar

João Victor Chaves de Oliveira jaozinfs

View GitHub Profile
@jaozinfs
jaozinfs / timerPeriodic.kt
Created September 22, 2020 14:16
Código que executa um temporizador periodico
val timer: TimerTask = object : TimerTask() {
override fun run() {
Handler().post {
//change current page
}
}
}
Timer().schedule(timer, DEFAULT_DELAY, DEFAULT_PERIOD)
@jaozinfs
jaozinfs / flowLaunch.kt
Created September 22, 2020 14:27
Inicia um flow e printa os resultados coletados
GlobalScope.launch {
increase(DEFAULT_DELAY).collect { currentValue->
print("Current value: $currentValue")
}
}
@jaozinfs
jaozinfs / flowIncrease.kt
Created September 22, 2020 14:25
Flow incrementador
suspend fun increase(delay: Long):Flow<Int> = flow {
var start = 0
do {
emit(start)
delay(delay)
start++
} while (coroutineContext.isActive)
}
@jaozinfs
jaozinfs / flipModuleFlow.kt
Created September 22, 2020 14:31
Retorna um flow que emite inteiros do startPosition até count, quando chega no final ele é reiniciado
fun flipModuleFlow(startPosition: Int, count: Int, delayMillis: Long = 2_000) = flow {
var s = startPosition % count
do {
emit(s)
delay(delayMillis)
s = (s + 1) % count
} while (coroutineContext.isActive)
}
@jaozinfs
jaozinfs / slideViewPagerJob.kt
Created September 22, 2020 14:32
cancela e inicia um job do flow module
private fun startSlide() {
slideJob?.cancel()
slideJob = lifecycleScope.launchWhenCreated {
flipModuleFlow(pager.currentItem, movieImagesAdapter.getAdapterSize())
.collect { currentPosition->
pager.setCurrentItem(currentPosition, true)
}
}
}
@jaozinfs
jaozinfs / viewPagerOnPageChange.kt
Created September 22, 2020 14:33
Cria uma classe com callback para avisar quando trocar de pagina do ViewPager
inner class SlideTrailersCallback : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
startSlide()
}
}
pager.registerOnPageChangeCallback(SlideTrailersCallback())
@jaozinfs
jaozinfs / flowLaunchMapPar.kt
Last active September 22, 2020 14:39
Inicia o flow e mapeia números pares
GlobalScope.launch {
increase(DEFAULT_DELAY).map {
it / 2 % 0
}.collect {
print("Current value: $it")
}
}
@jaozinfs
jaozinfs / flowLaunchFirsts10.kt
Last active September 22, 2020 14:39
Inicia o flow e pega os 10 primeiros resultados emitidos
GlobalScope.launch {
increase(DEFAULT_DELAY).take(10).collect {
print("Current value: $it")
}
}
val hotChannelExemple = Channel<String>()
launch {
hotChannelExemple.send("um")
hotChannelExemple.send("dois")
hotChannelExemple.send("três")
hotChannelExemple.send("quatro")
}
repeat(2) { println("Collector 1 ${hotChannelExemple.receive()}") }
val coldFlowExemple = (1..3).asFlow()
coldFlowExemple.onEach {
println("delay")
delay(300)
}.collect { value ->
println("Collector 1 - ${value}")
}
println("--")