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
  • a

    AG

    08/23/2020, 8:57 AM
    Hi everyone, I’m getting
    IllegalStateException Flow invariant is violated emission from another coroutine is detected
    when running this code, is it possible to fix this without using channelFlow ?
    flow<Action> {
        val result = downloadFile(url, directory) { event: ProgressEvent ->
            emit(DownloadProgress(event))
        }
        emit(DownloadFinished("path"))
    }.onEach { L.d(it) }.launchIn(viewLifecycleOwner.lifecycleScope)
    downloadFile method
    suspend fun downloadFile(
        url: String, fileDir: String, onProgressEvent: suspend (event: ProgressEvent) -> Unit = {}) {
     val progressChannel = Channel<ProgressEvent>()
    
     CoroutineScope(coroutineContext).launch {
         progressChannel.consumeAsFlow().collect { onProgressEvent.invoke(it) }
      }
    /* rest of the code */
    }
    z
    • 2
    • 5
  • c

    Carrascado

    08/23/2020, 3:34 PM
    What is the difference between
    (1..3).asFlow().onEach { number -> println("$number") }.collect()
    And
    (1..3).asFlow().collect { number -> println("$number") }
    Why would I want to use
    onEach
    when I can use
    collect
    directly?
    a
    f
    j
    • 4
    • 7
  • c

    Carrascado

    08/23/2020, 4:06 PM
    Ok I'm still learning about coroutines, and I'm a bit confused with the coroutines builders zoo... Is this all correct? • launch: Creates a new coroutine. Code below
    launch {}
    continues being executed instantly (although because structured concurrency, coroutine will finally wait for its children to finish). • async: Creates a new coroutine. Code below
    async {}
    continues being executed instantly (although because structured concurrency, coroutine will finally wait for its children to finish). • runBlocking: Creates a new coroutine. Execution is blocked. Code below
    runBlocking {}
    won't execute until runBlocking has ended. • coroutineScope: Creates a new coroutine. Execution is suspended (it's the suspending version of runBlocking). Code below
    coroutineScope {}
    won't execute until coroutineScope has ended. Now, if this is correct, the only coroutine builder whose name makes sense is runBlocking 🤷‍♂️ The other ones seem to have absolutely random names. The 4 coroutine builders "launch" the coroutine, two of them are "asynchronous" in some sense (both launch and async), and 4 of 4 again have a "coroutine scope", what am I not understanding here? Why do they have these names?
    z
    j
    t
    • 4
    • 69
  • g

    Gopal S Akshintala

    08/24/2020, 11:55 AM
    Can someone please help me with a sensible close to real-world usecase/example, where Coroutines are better than ExecutorService (say with pool count = no.of cores), for NON-blocking operations? (without using
    delay()
    )
    r
    g
    • 3
    • 15
  • u

    uhe

    08/24/2020, 2:27 PM
    Hey guys. I was playing around with using
    Result
    as a return type and ran into a weird issue. Does anybody know if this is already known? I couldn't find anything in the issue tracker.
    suspend fun foo() = suspendCancellableCoroutine<Unit> {
            thread {
                it.resumeWithException(RuntimeException("foo"))
            }
        }
    
        suspend fun fooWithResult(): Result<Unit> = runCatching { foo() }
    
        @Test
        fun resultTest() = runBlocking {
            // when fooWithResult is not inlined the exception is not caught by "runCatching"
            val result = fooWithResult() 
            Assertions.assertTrue { result.isFailure }
            delay(5000)
            Unit
        }
    The test passes if I mark
    fooWithResult
    as inline. Without it the exception is not caught by
    runCatching
    a
    i
    • 3
    • 6
  • r

    ryan413

    08/24/2020, 3:08 PM
    When returning a Coroutines JDK Future to a Java library, what’s the best way to do this?
    fun returnFuture(): CompleteableFuture<String> {
      return runBlocking {
        future {
          // blocking code
          "result"
        }
      }
    }
    or
    fun returnFuture(): CompleteableFuture<String> {
        return GlobalScope.future {
          // blocking code
          "result"
        }
      }
    }
    We have coroutine code further up the chain that then calls GraphQL-java, which in turn is wired with DataFetchers that implement an interface returning a CompleteableFuture. Ideally we want to share the same coroutine context throughout (so we can leverage MDC via
    MDCContext
    , etc.)
    s
    • 2
    • 5
  • j

    jean

    08/24/2020, 6:20 PM
    I’m trying to understand how that rule works, particularly
    this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher
    class CoroutineTestRule : TestWatcher(), TestCoroutineScope by TestCoroutineScope() {
    
        override fun starting(description: Description?) {
            super.starting(description)
            Dispatchers.setMain(this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher)
        }
    
        override fun finished(description: Description?) {
            super.finished(description)
            Dispatchers.resetMain()
        }
    }
    What does it do exactly? While debugging, I see that
    this.coroutineContext[ContinuationInterceptor]
    returns a
    TestCoroutineDispatcher
    , is that because the rule implement TestCoroutineScope which has a TestCoroutineDispatcher as default dispatcher?
    o
    • 2
    • 1
  • c

    camdenorrb

    08/24/2020, 7:03 PM
    How would you go about making a blocking method such as
    ByteBuffer.allocateDirect(bufferSize)
    suspending, would you need to make a threadpool and do callbacks to unsuspend a coroutine or is there a better way?
    o
    m
    +3
    • 6
    • 178
  • a

    Andrea Giuliano

    08/25/2020, 7:28 AM
    Hi guys, question on the @ExperimentalCoroutinesApi, is that safe to use them in production? I’ve seen a bunch of interesting components marked like that but I’m a bit scared to use them because of the annotation. What do you do in this case?
    t
    g
    • 3
    • 17
  • l

    Luis Munoz

    08/26/2020, 3:27 AM
    In a flow why doesn't catch capture errors for an onEach?
    t
    • 2
    • 6
  • l

    Lukas Lechner

    08/26/2020, 7:48 AM
    Hi! In a coroutine, we often want to use try-catch to catch all exceptions except
    CancellationExceptions
    . If we would catch
    CancellationExceptions
    , the Coroutine would continue to run until the next suspension point instead of cancel itself. Is there some convenience function in the stdlib that does this? Or have you written your own one?
    o
    • 2
    • 1
  • s

    Simon Lin

    08/26/2020, 7:56 AM
    message has been deleted
    l
    a
    s
    • 4
    • 8
  • a

    Andrea Giuliano

    08/26/2020, 7:57 AM
    Hi! I saw around a bunch of example where suspending function gets defined with coroutineScope like in
    suspend fun myFun() = coroutineScope {}
    I wonder, given that a suspending function must be called within a scope, what’s the point of creating a new scope like in there?
    o
    z
    • 3
    • 14
  • r

    rrva

    08/26/2020, 11:49 AM
    We are using coroutines-debug with DumpCoroutines but we are not getting all the active coroutines in the dump. How is this possible?
    • 1
    • 1
  • a

    Andrea Giuliano

    08/26/2020, 2:58 PM
    Sorry folks, I have another question around suspending function and structured concurrency. As far as I understood, suspect modifier will make the function suspendable, which means that the underneath thread can continue doing some work. So far so good. Now say that I have a function like this
    suspend fun doSomething() = coroutineScope {
       val channel: Channel<Int> = Channel(capacity)
       val results = aggregator.aggregate(channel)
       channel.close()
       results
    }
    where
    aggregator
    is a class that exposes a suspending function
    aggregate
    that uses the channel to listen to messages with
    channel.receive()
    Now, would
    channel.close()
    be ever invoked before the aggregator finishes to receive all the messages? Or since I’m not creating a new scope (by using launch or async for example) guarantees that each line of my snippet is executed one after the other finishes? And if that’s the case what’s the purpose of marking a function like
    aggregate()
    with a suspend modifier (although it suspends since it will wait for mesages in the channel)?
    z
    j
    • 3
    • 22
  • c

    Carrascado

    08/26/2020, 6:43 PM
    There really is no way to avoid passing the channel as an argument and avoid
    produce
    ? I don't want to avoid produce, it's just for curiosity
    o
    a
    • 3
    • 17
  • r

    rrva

    08/26/2020, 9:06 PM
    can I combine kotlinx.coroutines.sync.Semaphore.acquire and kotlinx.coroutines.withTimeout ?
    import kotlinx.coroutines.sync.Semaphore
    import kotlinx.coroutines.withTimeout
    
    private val concurrentRequests = Semaphore(50)
    
    suspend fun foo() {
        withTimeout(10) {
            concurrentRequests.acquire()
        }
        try {
            doStuff()
        } finally {
            concurrentRequests.release()
        }
    }
    o
    l
    • 3
    • 6
  • f

    Fernando Branbila Cunha Junior

    08/26/2020, 11:07 PM
    Hey guys, i'm new to coroutines and have being searching for some open souce web project to try to understand more and see how/where can i apply in real world cases, but couldn't found. Can you guys recommend any?
    o
    l
    • 3
    • 9
  • a

    Andrea Giuliano

    08/27/2020, 10:14 AM
    Hi guys, if I want to declare an interface with a method that runs in the scope of the caller, is that ok to do something like
    interface MyGuy {
      suspend fun CoroutineScope.doSomething()
    }
    or is there a better way when it comes to interface declaration?
    a
    g
    • 3
    • 15
  • f

    Fabio

    08/28/2020, 1:47 AM
    I loved the way the book "Kotlin in action" explains things, not only as a reference but as a way to go back to when I can write some code but not sure about some details. • Is there plans to make a new edition for coroutines? • is there a different book that covers coroutines? The official docs and the official / unoficcial blog posts are good, but they can't replace a good book for some situations.
    👍 4
    r
    • 2
    • 2
  • l

    Lukas Lechner

    08/28/2020, 8:53 AM
    Hi! I published a new blog post about “Why exception handling with Kotlin Coroutines is so hard and how to successfully master it!“. https://www.lukaslechner.com/why-exception-handling-with-kotlin-coroutines-is-so-hard-and-how-to-successfully-master-it/. I hope I can help a few people with this complex subject!
    👏 9
    😍 2
    t
    • 2
    • 1
  • b

    bsimmons

    08/28/2020, 11:56 AM
    Hey all, so I want to prevent making duplicate requests to a server. Does it make sense to store a bunch of
    Deferred<T>
    s and reuse them? Or is this a coroutine anti-pattern? I'm pretty new to coroutines so I'm just wonder if there is a better way.
    private val notesDeferred = HashMap<String, Deferred<Resource<String>>>()
    suspend fun getNotes(id: String): Resource<String>{
        if(notesDeferred.containsKey(id) && notesDeferred.get(id)!!.isActive){
            return notesDeferred.get(id)!!.await()
        } else {
            val newRequest = GlobalScope.async {
                remoteSource.getNotes(id)
            }
            notesDeferred.put(id, newRequest)
            return newRequest.await()
        }
    }
    w
    • 2
    • 5
  • a

    Andrea Giuliano

    08/28/2020, 4:59 PM
    Hi guys, I’m experimenting exception handling inside the launch, and I’ve created a very small test to do this
    @Test
        fun testingScope() = runBlocking {
            myfun1()
        }
    
        suspend fun myfun1() = coroutineScope {
            val handler = CoroutineExceptionHandler { _, exception ->
                println("CoroutineExceptionHandler got $exception")
            }
    
            launch(handler) {
                throw Exception()
            }
        }
    the test is failing because the exception gets bubbled up to the runblocking although I’m using an exception handler. Doing some debugging I’ve seen that the handler is set in the right child context, but still never called. Does anybody know why?
    s
    e
    • 3
    • 6
  • p

    pambrose

    08/28/2020, 6:48 PM
    On a similar note, I see old dependencies in ktor-client-core-jvm as well:
    |    +--- io.ktor:ktor-client-core-jvm:1.4.0
    |    |    +--- org.jetbrains.kotlin:kotlin-stdlib:1.4.0 (*)
    |    |    +--- org.slf4j:slf4j-api:1.7.30
    |    |    +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.4.0
    |    |    +--- org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8-native-mt-1.4.0-rc -> 1.3.9 (*)
    as well as ktor-network:
    |    |              +--- io.ktor:ktor-network:1.4.0
    |    |              |    \--- io.ktor:ktor-network-jvm:1.4.0
    |    |              |         +--- org.jetbrains.kotlin:kotlin-stdlib:1.4.0 (*)
    |    |              |         +--- org.slf4j:slf4j-api:1.7.30
    |    |              |         +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.4.0
    |    |              |         +--- org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8-native-mt-1.4.0-rc -> 1.3.9 (*)
    |    |              |         \--- io.ktor:ktor-utils:1.4.0 (*)
    a
    • 2
    • 2
  • l

    louiscad

    08/29/2020, 5:43 PM
    @pambrose You're getting kotlinx.coroutines 1.3.7, not 1.3.9
    r
    • 2
    • 2
  • r

    Ryan Pierce

    08/29/2020, 9:07 PM
    I am trying to enable Coroutine Debugging in Android Studio 4.0.1. I am using
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9
    coroutines and the
    1.4.0-release-Studio4.0-1
    Kotlin plugin. However, I don't see coroutines in my debugger menu as shown below. I've restarted and have
    Disable coroutine agent
    un-checked. What am I missing?
    r
    • 2
    • 2
  • s

    Simon Lin

    08/31/2020, 9:48 AM
    infix fun <E, R> ReceiveChannel<E>.zip(
        other: ReceiveChannel<R>
    ): ReceiveChannel<Pair<E, R>> (source)
    is deprecated. What is the alternative?
    e
    • 2
    • 4
  • m

    Maciek

    08/31/2020, 12:02 PM
    is there a way to close a channel and drop not yet consumed elements?
    b
    • 2
    • 3
  • s

    Sebastien Leclerc Lavallee

    08/31/2020, 2:55 PM
    Hi! I’m using AppAuth on Android to login to my backend and coroutines (ktor) on my transport layer to call APIs on that backend. I need to pass an access token to each of my calls. Using AppAuth I refresh this token with the
    AuthState.performActionWithFreshTokens(callback: (freshToken: String?))
    which uses a callback to give me the fresh token. And my transport service uses coroutines, something like:
    class TransportService {
      suspend fun getAllTasks(): List<Task> {
        authState.performActionWithFreshToken() { freshToken ->
          return ktorClient.get<List<Task>>()
        }
      }
    }
    Now, I have an error where I use the ktor client:
    suspend function can be called only within coroutines scope
    . That is because the callback function is not a coroutine scope. If I create a new scope within the callback, will this work well with the main function? What can I do to keep my transport with suspend function and not use completion handler everywhere? Thanks 🙂
    s
    • 2
    • 6
  • a

    ansman

    08/31/2020, 3:56 PM
    I suppose I could get the parent job inside my non cancellable block and add a cancellation listener which throws a cancellation exception
    b
    • 2
    • 9
Powered by Linen
Title
a

ansman

08/31/2020, 3:56 PM
I suppose I could get the parent job inside my non cancellable block and add a cancellation listener which throws a cancellation exception
b

bezrukov

08/31/2020, 5:28 PM
You should be able simply pass parentJob to withContext instead of noncancellable
a

ansman

08/31/2020, 5:29 PM
Ah, of course. A much more elegant solution 👌
I probably need an
ensureActive()
after my
withContext
since I don't think it'll throw if the job has been cancelled during the delay
b

bezrukov

08/31/2020, 5:32 PM
Nope, it should work as is
a

ansman

08/31/2020, 5:45 PM
Did they change this? I thought it was only when it resumes it checks for this?
No, I need an `ensureActive()`:
runBlocking {
    val parent = Job()
    val child = launch {
        withContext(parent) {
            delay(100L)
        }
        println("After")
    }
    delay(50L)
    child.cancel()
}
This code still prints after
Adding a
ensureActive()
before
println
it works as expected
b

bezrukov

08/31/2020, 5:50 PM
Ah, i thought you're about putting ensureActive directly after delay (withing withcontext block)
a

ansman

08/31/2020, 5:50 PM
Ah, yeah that'd do nothing haha
View count: 4