Skip to content

Instantly share code, notes, and snippets.

@lgtout
lgtout / amb_using_jobs_to_cancel_racers_and_emitting_failures.kt
Last active April 8, 2022 00:07
Experiment implementing amb/race operator using flow and without directly using channels
@OptIn(FlowPreview::class)
fun <A> Flow<A>.ambUsingJobsToCancelRacersAndEmittingFailures(
vararg others: Flow<A>
): Flow<Either<Throwable, A>> = flow {
val parentJob = currentCoroutineContext()[Job]!!
(listOf(this@ambUsingJobsToCancelRacersAndEmittingFailures) + others).foldIndexed(
Pair(emptyList<Job>(), emptyList<Flow<Pair<Int, Either<Throwable, A>>>>())
) { index, acc, curr ->
val job = Job(parentJob)
val flow = curr.map { Pair(index, it.right() as Either<Throwable, A>) }
@lgtout
lgtout / SystemUnderTest.kt
Last active December 17, 2021 22:42
Eliminate indirection due to interfaces while preserving stubbing and enforcing a narrow API surface
@file:Suppress("UNREACHABLE_CODE")
package com.lagostout.extensions
interface SystemUnderTest {
companion object
}
//fun SystemUnderTest.f1(): String = "f1" + f2() // Test this first without testing f2
//fun SystemUnderTest.f2(): String = "f2" // Test this second without testing f1
fun resolveDeepLink(
lifecycleScope: LifecycleCoroutineScope,
lifecycle: Lifecycle,
handler: DefaultScreenDeepLinkHandler,
provider: String,
json: JSONObject,
) {
val cancellable = cancelOnLifecycleStopAndRetryOnStartApiCallbackTask<Boolean>(
lifecycle, lifecycleScope, {
// Do something with result
@lgtout
lgtout / withContext_cancellation.kt
Last active July 22, 2021 01:34
withContext cancellation
import kotlinx.coroutines.*
import java.util.concurrent.ThreadLocalRandom
fun main() {
val job = GlobalScope.launch {
Thread.sleep(1000)
try {
println(1)
withContext(CoroutineName("foo")) {
val rnd = ThreadLocalRandom.current()
@lgtout
lgtout / listing.kt
Last active November 7, 2020 22:41
package chapter8.sec3.listing3
import arrow.core.getOrElse
import arrow.core.toOption
import chapter8.Falsified
import chapter8.MaxSize
import chapter8.Passed
import chapter8.RNG
import chapter8.Result
import chapter8.SimpleRNG
@file:Suppress("FunctionName")
package com.lagostout.bytebybyte.dynamicprogramming
import kotlin.math.absoluteValue
import kotlin.math.sign
object MatrixPath {
fun computeWithRecursionAndBruteForce(
@lgtout
lgtout / HomeGuesser.groovy
Last active March 10, 2017 04:54
Home location guesser for Sense360
package com.sense360
class HomeGuesser {
/**
* A location, consisting of latitude and longitude.
* Rounds coordinates provided to 3 decimal places.
* Compares by value, not reference.
*/
static class Location {