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

    marcoferrer

    02/17/2019, 9:04 PM
    I would assume that one of its children havent completed or yield early enough to cancel futher processing
    s
    g
    • 3
    • 2
  • s

    serebit

    02/17/2019, 11:20 PM
    Any plans to support the actor model in kotlin/native code?
    b
    • 2
    • 1
  • j

    Jaroslav

    02/19/2019, 6:12 AM
    Any examples on how to use channels on iOS? I have a library that expects me to give a
    ReceiveChannel
    object, but in iOS I cannot instantiate
    Kotlinx_coroutines_core_nativeReceiveChannel
    because it has no accessible initializers
    d
    y
    • 3
    • 6
  • t

    tatyana

    02/19/2019, 12:00 PM
    Hi. guys! I’m stuck with an issue in coroutines with switching back to the main thread after I updated - the kotlin version from ‘1.2.70’ to ‘1.3.20’ - the gradle plugin versino “3.2.1” to “3.3.1" I’m still using coroutines experimental lib version 0.19 : org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19 org.jetbrains.kotlinx:kotlinx-coroutines-android:0.19 The output is of that code is: I/System.out: Thread launchUI coroutine main I/System.out: Thread inside coroutine is ForkJoinPool.commonPool-worker-0 I/System.out: Thread after coroutine join ForkJoinPool.commonPool-worker-0 Also, I see the same with not switching to Main thread when use actor with default context(CommonPool) and then via the channel notify about updates and in consumeEach the thread didn’t change to main. Does anybody having such troubles?
    -.txt
    o
    s
    +2
    • 5
    • 9
  • p

    pardom

    02/19/2019, 4:35 PM
    Any of you coroutine pros want to tell me everything that is wrong with this function? I’m not 💯 with coroutines yet and have nobody to do reviews: https://github.com/pardom/oolong/blob/effect-typealias/oolong/src/main/kotlin/oolong/Oolong.kt#L12
    d
    • 2
    • 14
  • c

    cbruegg

    02/19/2019, 6:26 PM
    You've missed a
    return
    in case
    response.body()
    is null, i.e. the
    let
    path is not executed
    h
    • 2
    • 4
  • b

    basher

    02/20/2019, 2:54 AM
    I want to create a Dispatcher that limits concurrency to 1, but I don’t want the expense of creating a new thread dispatcher. Is there a way to create a limited concurrency dispatcher from the Default dispatcher?
    g
    h
    p
    • 4
    • 13
  • s

    seb

    02/21/2019, 3:22 AM
    hello everyone. I came here to ask about https://github.com/Kotlin/kotlinx.coroutines/issues/172 . I have been looking up and down google/stackoverflow/github to find a good example for this pattern, with no success. In the github issue, user gildor said "This pattern is so often, I see questions about implementation at least each week on Kotlin Slack
    #coroutines
    channel", so I figured I come here ^^ Anyone have a link for an example? Thank you so much.
    g
    • 2
    • 3
  • l

    Landerl Young

    02/21/2019, 8:53 AM
    Lazy async inside suspend function blocks forever? I have such code:
    fun main() = runBlocking {
            sth().await()
        }
    
        suspend fun sth() = coroutineScope {
            async(start = CoroutineStart.LAZY) {
                println("async execution")
            }
        }
    The main function blocks forever, and the “async execution” is never printed. Could anyone give a hand, thanks. 😘
    g
    • 2
    • 11
  • s

    sdeleuze

    02/21/2019, 9:05 AM
    FYI I have created https://youtrack.jetbrains.com/issue/KT-30042
    b
    • 2
    • 1
  • a

    Antanas A.

    02/21/2019, 9:11 AM
    Hi, Is it possible to make suspend function calls to tail recursive when nested function calls outer function? Now in the example I'm getting stackoverflow. Do anyone have a suggestions what the proper way to implement this logic?
    suspend fun connectToSocket() {
                suspend fun process(session: DefaultClientWebSocketSession) {
                    while (session.isActive) {
                        session.incoming.onReceiveOrNull { frame ->
                            if (frame == null) {
                                session.close()
                                delay(2000)
                                connectToSocket() // <- do reconnect
                            }
                        }
                    }
                }
                process(startSession())
            }
            connectToSocket()
    s
    • 2
    • 5
  • a

    ansman

    02/21/2019, 3:30 PM
    I’m getting a crash on Android when I cancel my job, it seems like my uncaught exception handler is being called when one of the children is being cancelled. The exception is
    JobCancelledException
    which I thought was never supposed to cause a crash
    l
    • 2
    • 2
  • a

    ansman

    02/21/2019, 4:27 PM
    Is there any way to handle dropped return values from a suspending coroutine? Say I do this:
    fun processImage() {
      val file = createFile()
      try {
        // Do stuff with the file
      } finally {
        file.delete
      }
    }
    
    suspend fun createFile(): File = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
      return File.createTemporaryFile("foo", "temp")
    }
    There is a case where
    createFile
    has finished but
    processImage
    has not yet been resumed. If during this time the job is cancelled we’ll never get a chance to clean up the file. Is there a way around this?
    u
    t
    +2
    • 5
    • 35
  • s

    spierce7

    02/21/2019, 4:36 PM
    Can anyone explain what
    CoroutineStart.ATOMIC
    does? The documentation isn't very clear to me.
    a
    u
    • 3
    • 8
  • h

    Herko

    02/22/2019, 11:53 AM
    If I know my block will execute in the same coroutine context, how can I achieve the above by passing something into the block?
    Suspension_functions_can_be_called_only_within_coroutine_body.kt
    u
    t
    • 3
    • 2
  • i

    itasyurt

    02/22/2019, 3:16 PM
    Hello, I have a question about fixed thread pools. I see that fixed thread pools are now obsolete https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-fixed-thread-pool-context.html Is there any suggested way to replace this? or should we continue with newFixedThredPoolContext (or java style executors) (Sorry for crospostng from #general)
    w
    • 2
    • 5
  • h

    Herko

    02/22/2019, 3:29 PM
    We have a case where we need coroutines to work with a Java library with lambdas in-between two Kotlin libraries with coroutines. What would be the most elegant way to make this snippet work?
    Chained_coroutines_with_Java_libraries.kt
    g
    • 2
    • 13
  • h

    Herko

    02/22/2019, 5:45 PM
    Updated_the_above_snippet_for_a_bit_more_context_on_my_library_mixing_issue.kt
    g
    • 2
    • 10
  • b

    basher

    02/23/2019, 3:47 AM
    When you call
    .freeze()
    on an object, somewhere along the line it calls
    FreezeSubgraph
    internally. What is it that determines what is part of an object's subgraph that also gets frozen as a part of that object's freeze operation?
    r
    • 2
    • 2
  • k

    Kulwinder Singh

    02/23/2019, 10:45 AM
    launching
    coroutine
    takes more than 700+
    millis
    . is it normal ? ,does
    launch
    builder takes that much of time?,i'm using this in android while displaying splash screen and then after 3 seconds delay closing splash
    -.kt
    l
    a
    • 3
    • 9
  • i

    ibcoleman

    02/23/2019, 6:05 PM
    (Sorry, hit send too soon...)
    getTESTInventoryPage(pg: Int)
    makes a long-running SOAP call. I expected things to blow up--instead it appears to make the calls in an arbitrary order, but eight at a time (which happens to be the number of virtual cores on my machine. Which is exactly what I want. Which is extremely suspicious... 🙂
    d
    • 2
    • 3
  • f

    Felix

    02/23/2019, 8:09 PM
    Hi. I need to create an actor that will own some mutable state and offer a request-response interface to manipulate it. What is the proper way to achieve that with coroutines and channels? Perhaps: - One single inbound channel that the clients use to send requests. - Each client creates its own reply channel, that is added to the request. - The actor coroutine sequentially fetch requests from the inbound channel, processes them, and sends the response to the reply channel referenced in the request. So, there will be a single request channel and one reply channel per client. Does this make sense? Is it possible to avoid having a reply channel per client?
    d
    • 2
    • 2
  • y

    yschimke

    02/24/2019, 10:19 AM
    Is there a clear pattern for launching true background work? Does supervisorScope instead of coroutineScope allow the work to continue in the background, while coroutineScope returns sooner?
    r
    s
    +2
    • 5
    • 7
  • a

    ansman

    02/24/2019, 4:14 PM
    What’s more idiomatic:
    fun events(channel: SendChannel<Event>)
    fun events(scope: CoroutineScope): ReceiveChannel<Event>
    In my case I need to add a listener when calling
    events
    and remove it when the channel is closed
    d
    d
    • 3
    • 24
  • p

    Paulius Ruminas

    02/25/2019, 6:37 AM
    Hello, why does it not print 1 2 3
    runBlocking {
                val producer = async {
                    produce {
                        send(1)
                        send(2)
                        send(3)
                    }
                }
    
                launch {
                    producer.await().consumeEach { println(it) }
                }
            }
    g
    • 2
    • 24
  • c

    cbruegg

    02/25/2019, 5:14 PM
    For such cases, I usually do something like this:
    var delayedJob: Job? = null
    
    fun onEvent() {
      delayedJob?.cancel()
      delayedJob = launch {
        delay(1000)
        // Do stuff
      }
    }
    n
    • 2
    • 2
  • i

    ivan.savytskyi

    02/25/2019, 8:13 PM
    is it thread safe to iterate over job’s children
    job.children.toList()
    ? By looking into source seems should be fine, but want to confirm
    b
    e
    e
    • 4
    • 5
  • a

    antonis

    02/26/2019, 8:05 AM
    Hello, I’m getting the attached warning in a suspend function inside an Android activity that implements the CoroutineScope. The code seems to work as expected but I’m a bit confused with the warning. Any ideas?
    -.txt
    g
    s
    • 3
    • 24
  • m

    minivac

    02/26/2019, 10:37 AM
    Mutex is there but I need the permits logic of semaphores
    g
    c
    j
    • 4
    • 21
  • v

    voddan

    02/26/2019, 2:06 PM
    Hello! I have a typical task of wrapping blocking IO calls into coroutines. Please point me to a working code example of that which supports job cancelation. Thank you
    l
    g
    s
    • 4
    • 10
Powered by Linen
Title
v

voddan

02/26/2019, 2:06 PM
Hello! I have a typical task of wrapping blocking IO calls into coroutines. Please point me to a working code example of that which supports job cancelation. Thank you
l

louiscad

02/26/2019, 2:17 PM
Blocking code does not support cancellation
➕ 2
g

gildor

02/26/2019, 2:53 PM
Only if this blocking code has some loop (like reading/writing to IO stream) or just a few steps, in this case you can check isActive property of coroutine to check cancellation state
👍 1
s

sitepodmatt

02/26/2019, 4:13 PM
Do you bother using isActive? I see in many of the jetbrains example they just let it hit the next suspending function and that throw cancellationexception and is ate the same. so they seem to use while(true) vs while(isActive)
obviously if no suspending function within the loop such fibanacci calc then you'd have to check isActive
l

louiscad

02/26/2019, 4:51 PM
You can also use
yield()
if the operation is actually a sum or loop of smaller I/O operations.
v

voddan

02/28/2019, 4:04 PM
Is there a safe way to abort the whole OS thread when I need to cancel the blocking operation?
g

gildor

02/28/2019, 4:30 PM
Yes, you can use Thread.interrupt(), but it's not a part of coroutines API (you need access to thread) and even with interrupt blocking code should support it (for example like Thread.sleep supports it, but it's not really widely supported API)
And if you can rewrite some blocking code to support thread interruption imo would be better rewrite it to support cancellation using coroutines
JVM doesn't support thread stopping anymore, it's not safe operation
v

voddan

03/01/2019, 3:16 PM
I see, thank you! I wish this was mentioned in the docs since I guess it is a common wish to use old blocking api with coroutines.
View count: 3