Skip to content

Instantly share code, notes, and snippets.

View jimmymorales's full-sized avatar

Jimmy Morales jimmymorales

View GitHub Profile
@jimmymorales
jimmymorales / WaitAtLeast.kt
Created June 1, 2021 22:27
Custom flow operator for waiting at least some time before getting first item.
/**
* Will wait at least [duration] for first item.
*/
fun <T> Flow<T>.waitAtLeast(duration: Duration): Flow<T> =
combine(flow { delay(duration); emit(Unit) }) { value, _ -> value }
@jimmymorales
jimmymorales / MviViewModel.kt
Created April 20, 2021 14:41
MviViewModel with ViewEventProducer
package com.advancedrecoverysystems.nobu.mvi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
@jimmymorales
jimmymorales / AutomaticCasts2.kt
Created July 5, 2020 22:15
Type Checking Automático en Kotlin 2
fun main() {
val obj: Any = "TGIK!"
// obj es convertido automaticamente a String en el lado derecho de `||`
if (obj !is String || obj.length == 0) return
// obj es convertido automaticamente a String en el lado derecho de `&&`
if (obj is String && obj.length > 0) {
println(obj.length) // obj es convertido automaticamente a String
}
@jimmymorales
jimmymorales / AutomaticCast.kt
Created July 5, 2020 22:13
Type Checking Automatico en Kotlin
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` se convierte automaticamente a `String` en este bloque
return obj.length
}
// `obj` aun es de tipo `Any` afuera del cuerpo del `if`
return null
}
@jimmymorales
jimmymorales / OperadorIs.kt
Created July 5, 2020 22:12
Operador `is` en Kotlin
fun main() {
val obj: Any = "Kotlin!"
if (obj is String) {
println("obj es un String")
}
}
@jimmymorales
jimmymorales / AutomaticCasts.js
Created July 5, 2020 04:07
Kotlin Automatic Casts transpiled to JavaScript
function getStringLength(obj) {
if (typeof obj === 'string' && obj.length > 0) {
return obj.length;
}
return null;
}
@jimmymorales
jimmymorales / AutomaticCasts.java
Last active July 5, 2020 04:07
Kotlin Automatic Cast decompiled to Java
public final class AutomaticCasts {
@Nullable
public static final Integer getStringLength(@NotNull Object obj) {
Intrinsics.checkParameterIsNotNull(obj, "obj");
return obj instanceof String && ((String)obj).length() > 0 ? ((String)obj).length() : null;
}
}