https://kotlinlang.org logo
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
  • d

    Derek Berner

    03/04/2019, 8:36 PM
    Quick question - is there currently any way to use coroutines with SQL databases when targeting the JVM? Aside from using
    <http://Dispatchers.IO|Dispatchers.IO>
    , that is. Specifically, our backend is MS SQL Server.
    s
    r
    s
    • 4
    • 5
  • d

    Dias

    03/05/2019, 9:22 AM
    When I want a function to run few coroutines in it I do
    fun test() = coroutineScope { 
       launch()
       launch() 
    }
    is using
    fun test() = withContext(...) { 
      launch()
      launch()
    }
    equivalent to that? apart from the part where you need to pass some context element in it
    g
    • 2
    • 4
  • d

    Dias

    03/05/2019, 9:23 AM
    is this right use-case for coroutineScope and withContext?
    g
    • 2
    • 1
  • l

    louiscad

    03/05/2019, 11:26 AM
    Is there a shorter/better way to properly cancel the current suspending function?
    suspend fun cancelNow(): Nothing = suspendCancellableCoroutine<Nothing> { c -> c.cancel() }
    e
    • 2
    • 9
  • m

    mboudraa

    03/05/2019, 1:37 PM
    hey folks, i have this unit test which tests my dao correctly observe a database through a channel
    @Test
        fun `should receive updated data when querying all challenges`() {
            val initChallenges = mutableListOf(Challenge(...),Challenge(...))
    
            val newSurveyChallenge = SurveyChallenge(...)
    
            val expectedChallenges = listOf(
                initChallenges,
                initChallenges += newSurveyChallenge
            )
    
            initChallenges.forEach(challengeDao::addOrUpdate)
    
            runBlocking {
                val channel = repository.availableChallenges(coroutineContext)
    
                val actualChallengesLists = async(IO) {
                    channel.fold(mutableListOf<List<Challenge>>()) { list, challenges -> list.apply { add(challenges) } }
                }
    
                delay(300)
                challengeDao.addOrUpdate(newSurveyChallenge)
                delay(300)
                channel.cancel()
    
                assertThat(actualChallengesLists.await()).containsExactlyElementsIn(expectedChallenges).inOrder()
            }
    without those
    delay
    , my test fail because the database doesnt have the time to notify anything. But having a delay looks like a code smell to me. Is there a better way to test this behavior? For the record I use
    sqldelight
    and
    robolectric
    to test that
    g
    • 2
    • 2
  • s

    sitepodmatt

    03/06/2019, 9:24 AM
    object CoroutineCrashTest {
        private val scope = GlobalScope + Job()
    
        fun run() = scope.launch(Dispatchers.Default) {
            doAwaitInside()
        }
    
        private suspend fun doAwaitInside() {
            supervisorScope {
              try {
                  testAsync().await()
              } catch (e: IllegalStateException) {
                  // catched but still crash
              }
            }
        }
    
        private fun testAsync() = scope.async(Dispatchers.Default) {
            throw IllegalStateException("test")
        }
    }
    l
    l
    • 3
    • 5
  • s

    sitepodmatt

    03/06/2019, 9:24 AM
    try that - untested
    l
    • 2
    • 1
  • g

    ghedeon

    03/06/2019, 1:36 PM
    It drives me crazy. Rx version works and Coroutine version is flaky and failing in 25% of the runs. Do I miss anything about
    GlobalScope.rxFlowable{}
    ?
    GlobalScope_rxFlowable__.kt
    g
    e
    • 3
    • 19
  • s

    Seri

    03/06/2019, 7:01 PM
    I’m seeing some odd behavior with
    CompletableDeferred
    . I’m using it to wrap an Android UI prompt, so I’m setting a
    lateinit var CompletableDeferred
    before launching the prompt, then completing it from the system callback once the user action is complete. However, the var is always
    null
    when I try to complete it. Is there an obvious flaw here, or a better approach?
    b
    • 2
    • 3
  • w

    Wouter Vegter

    03/07/2019, 9:19 AM
    we have a lot of problems with JobCancellationException causing our android app to hard-crash we already did a lot of research & tweaking to migitate this problem, but it keeps popping up this is what we do: - in Activity.onStart we create quite some (hierarchical) jobs that listens to all kinds of firebase data registrations - when some data changes via channel, we regularly need to stop some data observers and start new data observers via jobs/channels, for switching this data we use our own switchMap method we want to use kotlin&coroutines in our production app, but now we are in serious doubt whether coroutines and the JobCancellationExceptions are maybe not stable enough currently -> Is there anyone that has had a similar experience or can someone offer insight how we prevent JobCancellationException forcing our app to crash?
    v
    • 2
    • 5
  • v

    vngantk

    03/07/2019, 9:23 AM
    Has anyone implemented the Zookeeper distributed lock recipe using coroutines? The examples given in Zookeeper site and those provided by the Curator framework are of blocking mode. Since Zookeeper also provides async version for its API, I think it is possible to use its async API to implement a coroutines version of distributed lock.
    v
    • 2
    • 1
  • o

    Oleh Ponomarenko

    03/07/2019, 10:07 AM
    Hello guys! Please help me with Coroutines. I need to implement this: 1. Run my task in background mode 2. Stop the task in 30 seconds 3. Delay 10 seconds. 4. Repeat my cycle (1-3 points) infinitely https://prntscr.com/mu5xin (detailed on a picture)
    g
    s
    b
    • 4
    • 21
  • m

    Marcelo Hernandez

    03/07/2019, 7:05 PM
    When dealing with a lifecycle-aware component, such as a Presenter, where you may have repeated `onStart`/`onStop` toggling, is it okay to use
    cancelChildren()
    while never explicitly cancelling the parent
    Job
    itself? This way when
    onStart()
    is called, you can continue reusing the
    Job
    for launching more coroutines?
    w
    g
    • 3
    • 53
  • j

    Jag

    03/07/2019, 11:22 PM
    I understand that channels as of today are marked obsolete but I was looking to gain clarity on what the future of channels looks like (beyond what is described in issue #254). Could we still anticipate some form of a CSP like model -- facilitate communicating between coroutines? Are the proposed replacement of lazy async streams similar in concept to channels?
    ➕ 1
    b
    j
    +5
    • 8
    • 12
  • b

    basher

    03/08/2019, 5:55 AM
    Maybe you mean experimental?
    g
    j
    +2
    • 5
    • 8
  • d

    deviant

    03/08/2019, 3:02 PM
    is it possible to get coroutine scope object inside of coroutine? for example:
    private suspend fun <E> ReceiveChannel<E>.throttle(): ReceiveChannel<E> {
        // want to launch {} in current scope
    }
    w
    s
    +2
    • 5
    • 14
  • m

    mp

    03/08/2019, 3:04 PM
    When calling Jackson's
    ObjectReader#readValue()
    inside a suspending function, I get an inspection warning that it's an "Inappropriate blocking method call". However, I'm calling the variant that deserializes from a string, so there's no blocking i/o. Also I still get the warning if I throw that logic onto another dispatcher. What can I do about the warning other than suppress it?
    🤔 1
    l
    • 2
    • 1
  • h

    Hexa

    03/08/2019, 4:28 PM
    Could someone confirm if Kotlin coroutines are stackfull or stackless
    e
    p
    • 3
    • 39
  • p

    pardom

    03/08/2019, 4:29 PM
    stackless
    🇳🇴 1
    e
    • 2
    • 6
  • m

    matiaslev

    03/08/2019, 5:34 PM
    Like a repost from the #general channel but pointing to this specific course about coroutines. Not did it so far, but looks nice. And is free this weekend. https://www.pluralsight.com/courses/kotlin-using-coroutines
    :thumbsup_all: 2
    i
    • 2
    • 2
  • b

    bjonnh

    03/08/2019, 11:16 PM
    should I just run that in a IO?
    g
    • 2
    • 2
  • b

    bjonnh

    03/08/2019, 11:19 PM
    (that removes the warning but I'm not sure it is the right way)
    g
    • 2
    • 4
  • d

    Dico

    03/09/2019, 1:09 PM
    Sometimes I find a need for
    withScope
    instead of
    withContext
    . Now you have to write
    withContext(myScope.coroutineContext)
    but, given the intended purpose 😉 of
    CoroutineScope
    , I feel there should be a scope variant of it.
    d
    e
    • 3
    • 13
  • t

    thana

    03/10/2019, 3:52 PM
    is there any way to leverage webworkers when using coroutines on javascript?
    g
    • 2
    • 3
  • b

    bjonnh

    03/11/2019, 4:05 AM
    produce<String>(capacity = 1024) {
                input.forEachLine { async { send(it) } }
            }.map {
                async {
                    val tokenized = tokenizerFactory.create(pp.preProcess(it)).tokens.joinToString(" ")
                    tokenized + "\n"
                }
            }.map {
                output.appendText(it.await())
            }
    g
    s
    m
    • 4
    • 91
  • s

    spand

    03/11/2019, 9:38 AM
    Is
    Dispatchers.setMain
    also coming for js ?
    g
    b
    • 3
    • 16
  • t

    trathschlag

    03/11/2019, 12:45 PM
    fun main() {
        runBlocking {
            val job = launch {
                suspendCoroutine<Unit> {}
            }
    
            yield()
            job.cancel()
            println("goodbye")
        }
        println("exit")
    }
    prints
    goodbye
    and then hangs forever. Does anybody know why this happens? When removing the
    yield()
    it just works as expected.
    s
    s
    r
    • 4
    • 16
  • s

    Slackbot

    03/11/2019, 1:10 PM
    This message was deleted.
    g
    s
    • 3
    • 2
  • a

    ahulyk

    03/11/2019, 1:21 PM
    Hi Guys! Is there any difference in following shipnets:
    launch {
            val first = async(IO) {
                transactionDataRepository.getFist()
            }
            val second = async(IO) {
                transactionDataRepository.getSecond()
            }
        }
    and
    launch {
                withContext(IO) {
                    val first = async {
                        transactionDataRepository.getFist()
                    }
                    val second = async {
                        transactionDataRepository.getSecond()
                    }
                }
            }
    ???
    a
    • 2
    • 1
  • g

    Giorgio Antonioli

    03/11/2019, 1:48 PM
    Hi, I'm having a problem with
    BroadcastChannel
    .
    private val getChannel = BroadcastChannel<String>(1)
    
    fun myApiCallbackNotSuspended() {
        runBlocking {
            println("X") 
            getChannel.send("result")
            println("Y")
        }
    }
    
    suspend fun get(): String {
        val receiveChannel = getChannel.openSubscription()
        println("A")
         // It will invoke "myApiCallbackNotSuspended()" on the main thread after some time.
        myApiCall()
        println("B")
        val result = receiveChannel.receive()
        println("C)
        return result
    }
    The method
    myApiCallbackNotSuspended()
    is invoked and it sends the result to the channel. The problem is that
    receiveChannel.receive()
    remains stuck. I get the message in the following order: A B X Y without getting C
    m
    • 2
    • 2
Powered by Linen
Title
g

Giorgio Antonioli

03/11/2019, 1:48 PM
Hi, I'm having a problem with
BroadcastChannel
.
private val getChannel = BroadcastChannel<String>(1)

fun myApiCallbackNotSuspended() {
    runBlocking {
        println("X") 
        getChannel.send("result")
        println("Y")
    }
}

suspend fun get(): String {
    val receiveChannel = getChannel.openSubscription()
    println("A")
     // It will invoke "myApiCallbackNotSuspended()" on the main thread after some time.
    myApiCall()
    println("B")
    val result = receiveChannel.receive()
    println("C)
    return result
}
The method
myApiCallbackNotSuspended()
is invoked and it sends the result to the channel. The problem is that
receiveChannel.receive()
remains stuck. I get the message in the following order: A B X Y without getting C
m

marstran

03/11/2019, 1:53 PM
Can you provide
myApiCall
as well, so we can reproduce it?
g

Giorgio Antonioli

03/11/2019, 2:10 PM
myApiCall
is a method inside a library which is not open-source. I tried to reproduce the same behavior with another library and it works. It seems something related to "myApiCall" and channels used together. TBH I have no clue on what to check now.
View count: 3