https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
coroutines
  • u

    ursus

    03/14/2021, 2:13 PM
    Why does refCount behavior require to specify scope? Scope is implicit via last subscriber unsubscription
    a
    6 replies · 2 participants
  • s

    Simon Lin

    03/15/2021, 6:47 AM
    How to design a CoroutineScope that active when user login and cancel when user logout?
    j
    8 replies · 2 participants
  • s

    Scott Kruse

    03/15/2021, 4:03 PM
    So i have a coroutine that consumes a
    ReceiveChannel
    .
    MainScope
    is a basic scope tied to
    Dispatchers.Main
    -- For some reason, despite calling
    cancel()
    from the calling viewmodel's
    onCleared
    function, This job continues to run after back pressing and reentering the app. If i change the scope to
    viewmodelScope
    the coroutine is cancelled appropriately. Can anyone shed some light on this?
    fun run(params: Params, onEachResult: (any: Any) -> Unit) {   
    
          mainScope.job = mainScope.launch {
                run(params).consumeEach(onEachResult)
          }
    
       }
    
       fun cancel() {
            mainScope.job.cancel()
       }
    
        internal class MainScope(private val mainContext: CoroutineContext) : CoroutineScope {
    
            var job: Job = Job()
            private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
                showError(throwable)
            }
    
            override val coroutineContext: CoroutineContext = mainContext + job + exceptionHandler
    
            fun showError(t: Throwable) {
                Timber.e(t)
                throw t
            }
        }
    z
    9 replies · 2 participants
  • m

    melatonina

    03/15/2021, 4:13 PM
    Is this a good way to create a dispatcher which runs coroutines on a high priority thread?
    import java.util.concurrent.Executors
    
    import kotlinx.coroutines.asCoroutineDispatcher
    import kotlin.concurrent.thread
    
    fun highPriorityContext() = Executors.newSingleThreadExecutor { runnable ->
        thread(priority = Thread.MAX_PRIORITY) { runnable.run() }
    }.asCoroutineDispatcher()
    e
    b
    5 replies · 3 participants
  • s

    Simon Lin

    03/16/2021, 6:40 AM
    Can I suspend get the value by
    SharedFlow
    (replay is 1) like
    Channel::receive
    ? for example:
    suspend fun generateSomething() : String {
        val result = _channel.receive() // Change Channel to SharedFlow
        return "Result is $result"
    }
    e
    a
    2 replies · 3 participants
  • d

    Doru N.

    03/16/2021, 4:38 PM
    Hello, got a question on coroutines Flow. Is there a way of replicating RxJava 
    timeout
     operator on Kotlin Flow? Namely, for my use case, I want to emit values from a Flow downstream, until a timeout happened (timeout duration should reset after every new emission), then stop emitting (no error) ? The closest impl I see to what I need is the 
    debounce
     operator, with the diff that I need to close / complete the flow when timeout happens.
    e
    b
    7 replies · 3 participants
  • k

    knthmn

    03/17/2021, 8:34 AM
    I found this article from 2019 talking about the best practice of injecting dispatchers so that tests work well. Is this still the state of things? Just confirming because it sounds a little weird to me. Is there no way to change all dispatchers provided by
    Dispatchers
    to a test dispatcher when testing? https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/
    w
    4 replies · 2 participants
  • a

    adambl4

    03/17/2021, 10:48 AM
    Hey, why this test fails? I want to implement a “single instance job” which means there is should be only one active job with specific name in a scope
    @Test
        fun test() {
            val job = GlobalScope.launch(CoroutineName("my_name")) {
                delay(1000)
            }
    
            assertEquals("my_name", job[CoroutineName]?.name)
        }
    1 reply · 1 participant
  • s

    Shabinder Singh

    03/17/2021, 3:53 PM
    In my Project I am using Ktor to download *many Files*_(each almost 4mb_) I have a Coroutine Scope(IO) at App Level (_i.e., act_ive throught application Lifecycle.) Now as of now , I am Just *Blindly Launching coroutines(like 150 of them)* in this scope which download Files. Instead, I want to alter it to act as described Below: 1. Making this scope to only run a certain number of courtines parallelly say 4. 2. launching in this scope remains same, launch 150 or more coroutines all together and let the scope handle parallel downloads 3. A function , returning number of active/pending coroutines in this scope. Any help in pointing me in the right direction to correctly and efficiently implement this is appreciated!
    🤔 1
    m
    g
    2 replies · 3 participants
  • a

    Andrey B.

    03/17/2021, 4:16 PM
    Hello everyone.... Am I going crazy? In my Android ViewModel I have something like this:
    viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { someFunction() }
    ....
    fun someFunction(){}
    It's compiling!!! But whyyyy? Shouldn't someFunction() be suspendable??
    z
    a
    +2
    14 replies · 5 participants
  • a

    Astronaut4449

    03/17/2021, 5:28 PM
    JVM: Hi, has anyone ever implemented a suspend function like
    suspend fun <http://java.io|java.io>.File.readTextAsync(charset: Charset)
    or
    suspend fun java.nio.file.Path.readTextAsync(charset: Charset)
    that is cancellable?
    u
    2 replies · 2 participants
  • d

    Denis Sazonov

    03/18/2021, 9:37 AM
    Good morning/day/evening. I need a solution for the following case: There is a cache, and I need to get objects from different threads (rest controller). If there is no object in cache I need to fetch this object via network. So the problem - only single thread should execute the network request, but others should wait until object is fetched and cached. This is the solution I have in mind. Is it okay?
    Untitled
    u
    m
    5 replies · 3 participants
  • i

    igor.wojda

    03/18/2021, 11:05 AM
    What are the ways to fix this problem ?
    w
    i
    +2
    7 replies · 5 participants
  • f

    fal

    03/19/2021, 12:45 AM
    Hi, I'm learning coroutines (coming from Rx world) and I'm trying to find a good way to refresh my flows on ViewModel... So far what I've been thinking is creating a shared flow to represent refresh events, something like:
    private val refreshFlow =
        MutableSharedFlow<Unit>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST).apply {
          tryEmit(Unit)
        }
    
    init {
      fetchNews()
    }
    
    fun refreshData() {
      refreshFlow.tryEmit(Unit)
    }
    
    private fun fetchNews() {
      viewModelScope.launch {
        refreshFlow
            .flatMapLatest { fetchLatestNewsFlow() }
            ...
            .collect()
      }
    Is this ok? Are there any better solutions?
    e
    b
    9 replies · 3 participants
  • l

    Lilly

    03/19/2021, 1:37 AM
    Hi, I'm struggling with an specific implementation of my use case. I have a simple channel
    private val packetChannel: Channel<ResponsePacket> by lazy { Channel(Channel.UNLIMITED) }
    that receives
    ResponsePacket
    which is just a data class which holds a
    ByteArray
    . After making a request to the API that produces the packets, I offer it via the channel (packets are only offered on request and communication is sequential, so request waits until packet is offered). I would like to consume these packets via flow but some packets are different which require different actions on collection, see screenshot. I'm clueless how to achieve this. For case 1 I would have to request 3 packets and while packet A is received I would parse it but then would have to wait until packet B + C is received and parsed and then merge the results of these and emit the result or otherwise case 2. That's the part I can't get my head around. Some help is much appreciated 🙏
    e
    7 replies · 2 participants
  • s

    Sudhir Singh Khanger

    03/19/2021, 9:21 AM
    How do I run N network calls parallel-ly and wait for their response? Data {1, 2, 3, ... N} -> Response { Response1, Response2, Response3...ResponseN} I want to run the tasks parallel-ly and wait for their response separately without losing which response belongs to which data param.
    b
    2 replies · 2 participants
  • r

    rmyhal

    03/19/2021, 9:32 AM
    Hello, is there a something like
    withTimeout(time) { operation }
    but without canceling the operation? What I want to achieve: If an operation takes longer than
    N
    millis I want to have a callback about this and I want the operation to continue working. Something like:
    withTime(
        time = 500L, 
        block = { operation }, 
        onTimeOver = {  }
    )
    c
    s
    +1
    7 replies · 4 participants
  • m

    Marco Pierucci

    03/19/2021, 9:56 PM
    Hello everyone! Would :
    private val _event = MutableSharedFlow<S>(extraBufferCapacity = 1)
        val event: SharedFlow<S> get() = _event.asSharedFlow()
    be a correct alternative to
    Channels
    for single shots events? Or would events would still be dropped if there are no subscribers
    s
    j
    7 replies · 3 participants
  • f

    Fredrik Rødland

    03/20/2021, 4:37 PM
    Hi. Trying to dig into the docs & tutorials on https://kotlinlang.org/docs/coroutines-basic-jvm.html and https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/01_Introduction for the n-th time to try to get the grip on them 😉 The doc says that the following code will return an arbitrary number and I agree with it; we don’t wait for the coroutines to finish. However it does not for me - I’ve run it 20 times - each resulting in the sum being `500000500000`… (java 15, kotlin 1.4.31, coroutines 1.4.3, macOS) Any tips/insight as to why?
    package samples
    
    import kotlinx.coroutines.GlobalScope
    import kotlinx.coroutines.launch
    import java.util.concurrent.atomic.AtomicLong
    
    fun main() {
        val c = AtomicLong()
            for (i in 1..1_000_000L)
            GlobalScope.launch {
                c.addAndGet(i)
            }
            println(c.get())
    }
    PS! if this is better suited as question in #getting-started please tell me and I’ll move it there.
    z
    9 replies · 2 participants
  • n

    natario1

    03/20/2021, 6:37 PM
    What's the elegant way to have something like
    combine(flow1, flow2, ..., flowN, transform)
    that does not wait for all flows to emit the first value? I'd happily receive a smaller array if some flow does not have a value yet.
    e
    5 replies · 2 participants
  • c

    Ch8n

    03/21/2021, 9:12 AM
    Hi guys I'm trying to learn channels went through docs, I got lost after the fan-out section, and after watching

    this▾

    talk I'm totally a gone case 😛😵, can anyone share some uses cases of channels? examples or real-life use cases?
    m
    1 reply · 2 participants
  • n

    Natsuki(开元米粉实力代购)

    03/22/2021, 7:56 AM
    in my understanding, the first code fragment should behavior the same as the latter one, coz launch w/o explicit receiver adds the new created coroutine as a child of current coroutine, so cancel the collectLatest block will cause the child coroutine to cancel, which should leads to the same result as the latter code fragment
    :thread-please: 3
    k
    n
    2 replies · 3 participants
  • r

    Remy Benza

    03/22/2021, 9:28 AM
    does collecting two flows inside the same coroutineScope influence each other when the coroutine context is a
    SupervisorJob
    ?
    n
    k
    +1
    14 replies · 4 participants
  • s

    Se7eN

    03/22/2021, 4:43 PM
    Should I use
    <http://Dispatchers.IO|Dispatchers.IO>
    or
    Dispatchers.Default
    for drawing with canvas on a bunch of bitmaps (GIF frames)?
    b
    z
    +1
    9 replies · 4 participants
  • d

    Daniele B

    03/22/2021, 5:12 PM
    I am importing:
    val commonTest by getting {
        dependencies {
            implementation(kotlin("test-common"))
            implementation(kotlin("test-annotations-common"))
            implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3")
        }
    }
    and I am getting this:
    org.gradle.internal.resolve.ArtifactNotFoundException: Could not find kotlinx-coroutines-test-1.4.3-samplessources.jar (org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3).
    m
    e
    +1
    6 replies · 4 participants
  • t

    therealbluepandabear

    03/23/2021, 4:49 AM
    Why am I getting an unresolved reference here:
    g
    13 replies · 2 participants
  • n

    natario1

    03/23/2021, 10:16 AM
    What's the difference between executing some operations in a
    coroutineScope { }
    vs. just executing them in the outer scope? Assuming the outer context has a regular
    Job
    .
    b
    a
    +2
    11 replies · 5 participants
  • l

    Lilly

    03/23/2021, 4:54 PM
    Is there an equivalent for
    while (!packetChannel.isEmpty) {
    	packetChannel.receive()
    }
    in flows when I convert the channel to a flow:
    packetChannel.receiveAsFlow()
    Edit: I would like to consume the channel as a flow, but instead of collect all values then parse I would like to collect one value, parse it, wait for next one then emit final result
    d
    e
    +2
    25 replies · 5 participants
  • b

    Brian Dilley

    03/23/2021, 5:49 PM
    (reposting this question since i did it late at night and it didn’t get any responses): I’ve built a sharding library and i’m trying to add coroutine functionality to it. In the following snippet i’m hoping that it’s doing what I’m thinking it does (returns the first 
    true
     result that it finds):
    override fun emailExists(email: String): Boolean {
            val results = shards.asyncAll { userDao.emailExists(email) }
            return runBlocking {
                results.map { it.await() }
                    .firstOrNull { it }
            } ?: false
        }
    the shards.asyncAll method is:
    fun <T> async(
            shardId: Long,
            context: CoroutineContext = EmptyCoroutineContext,
            start: CoroutineStart = CoroutineStart.DEFAULT,
            block: suspend CoroutineScope.() -> T): Deferred<T> {
            return scope.async(context, start) {
                selectShard(shardId)
                block()
            }
        }
    
        fun <T> asyncAll(
            shardIds: Collection<Long> = this.shardIds,
            context: CoroutineContext = EmptyCoroutineContext,
            start: CoroutineStart = CoroutineStart.DEFAULT,
            block: suspend CoroutineScope.() -> T): List<Deferred<T>> {
            return shardIds.map { async(it, context, start, block) }
        }
    So first question is if that code above (
    emailExists
    ) will work, and the second question is: how can i change it so that the first 
    Deferred<Boolean>
     result that returns that is 
    true
     returns from the method (rather than it testing them in order as they come back - I’d like it so that the very first one that comes back with a result of 
    true
     triggers a return)
    m
    6 replies · 2 participants
  • t

    therealbluepandabear

    03/23/2021, 7:41 PM
    What are coroutines really in a more technical point of view?
    j
    e
    +2
    9 replies · 5 participants
Powered by Linen
Title
t

therealbluepandabear

03/23/2021, 7:41 PM
What are coroutines really in a more technical point of view?
j

jw

03/23/2021, 7:52 PM
switch statements?
😒uspend: 1
☝️ 3
👌🏼 1
❤️ 1
❓ 1
😅 1
e

ephemient

03/23/2021, 7:52 PM
https://github.com/JetBrains/kotlin/blob/document-coroutines-codegen/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/coroutines-codegen.md
👍 2
t

therealbluepandabear

03/23/2021, 7:54 PM
@ephemient Coroutines are a bit confusing to be honest 🥴
e

ephemient

03/23/2021, 7:54 PM
"switch statements" is fair. compiler rewriting your linear code into switch statements jumping to program states broken up at every suspend point
j

jw

03/23/2021, 7:54 PM

https://www.youtube.com/watch?v=YrrUCSi72E8▾

👆 1
➕ 1
e

ephemient

03/23/2021, 7:56 PM
I was going to say, try writing your own coroutines by hand first and then you'll understand why kotlin compiler does what it does. but I guess that talk summarizes that part too
😀 1
t

therealbluepandabear

03/23/2021, 8:19 PM
@ephemient thanks for this, I will watch it later 😄
u

ursus

03/23/2021, 8:55 PM
syntactic sugar over nested callbacks
n

Natsuki(开元米粉实力代购)

03/24/2021, 6:17 AM
IMHO 1. every suspend point split the original code into two parts of function (the previous part and the rest part), and compiler may optimize and implement this in a state-machine 2. since a suspend function is composed of two or more split function, you can decide whether to call the rest function or just return on the suspend point , 3. you can call the rest function immediately there's no significant difference from the not-split one 4. you can also just return and only call the rest function when some condition meets (i.e network request done) 5. compared to the original one, now you have a chance to decide to call the rest function, that's the point coroutine is, but it still looks like a aotimic function in literal code (at lest in source code level)
View count: 8