Skip to content

Instantly share code, notes, and snippets.

View fluidsonic's full-sized avatar

Marc Knaup fluidsonic

View GitHub Profile
@fluidsonic
fluidsonic / FlowCombineLatest.kt
Last active October 16, 2020 20:02
Fast flow combination
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
private val undefined = Any()
internal fun <T> Iterable<Flow<T>>.combineLatest(): Flow<List<T>> =
combineLatest { it }
@fluidsonic
fluidsonic / FlowShareIn.kt
Created October 11, 2020 15:36
Rudimentary Flow.shareIn with WhenSubscribed behavior until the official operator is launched
fun <T> Flow<T>.shareIn(scope: CoroutineScope): Flow<T> {
val upstream = this
var broadcastChannel: BroadcastChannel<T>? = null
val mutex = Mutex()
var subscriberCount = 0
return flow {
val activeChannel = mutex.withLock {
subscriberCount += 1
broadcastChannel ?: upstream.broadcastIn(scope).also {
@fluidsonic
fluidsonic / ParallelExecutor.kt
Last active January 24, 2023 05:51
Parallel coroutine execution with dynamic concurrency in Kotlin
// Dependencies:
// implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9")
// implementation("org.jetbrains.kotlinx:atomicfu:0.14.4")
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
import java.io.*
import kotlin.coroutines.*
@file:OptIn(ExperimentalTime::class)
import kotlinx.coroutines.*
import kotlin.time.*
suspend fun main() {
coroutineScope {
println("Launching tasks…")
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.*
import kotlin.coroutines.*
@Suppress("EXPERIMENTAL_API_USAGE")
suspend fun main() {
coroutineScope {
// same as Merge<Foo | Bar>
interface MergeOfFooAndBar {
a: number
b?: string
}
interface Foo {
a: number; // no b
}
interface Bar {
a: number; b: string
}
function logB(value: Merge<Foo | Bar>) {
console.log(value.b) // .b is now an optional 'string' property
interface Foo {
a: number; // no b
}
interface Bar {
a: number; b: string
}
function logB(value: Foo | Bar) {
console.log(value.b) // We cannot access .b as it isn't defined on Foo.
@fluidsonic
fluidsonic / Merge.ts
Created January 9, 2020 11:59
Merges a union type into a type with properties of all union components
type Merge<Union> = AddOptionalProperties<Union, keyof UnionToIntersection<Union>>
type AddOptionalProperties<Union, Properties extends keyof any> =
Union extends (infer Component)
? { [P in keyof Union]: Union[P] } & { [P in Exclude<Properties, keyof Union>]?: never }
: never
// https://stackoverflow.com/a/50375286/1183577
type UnionToIntersection<Union> =
(Union extends any ? (_: Union) => void : never) extends ((_: infer Component) => void) ? Component : never
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
import kotlin.reflect.jvm.isAccessible
class SomeClass {
var someProperty by observable(1)
}