Skip to content

Provide an API to race coroutines ("losers" are cancelled) #2867

@LouisCAD

Description

@LouisCAD

Hello,

I keep seeing this suspend functions racing use case being asked on Kotlin's Slack, and I personally need it quite often as it suits many needs in "coroutines-heavy" code.

I've been using my own solution for a long time now, which I also published as a library in Splitties for that (available on MavenCentral), and I didn't find any better API than raceOf({…}, { … }, …) and race { launchRacer { … } }.

Here is an example snippet of raceOf in action taken straight from the README of Splitties Coroutines:

suspend fun testCoroutinesRacing() {
    val result = raceOf({
        delay(3)
        "slow"
    }, {
        delay(0)
        "fast"
    })
    assertEquals(expected = "fast", actual = result)
}

and here's a permalink to the code of these 2 APIs.

Can this API or a better alternative be considered for addition inside kotlinx.coroutines?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions