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

    rogeralsing

    12/01/2018, 8:04 PM
    Also what happened to “asCompletableFuture” for Java interop ? is this still around?
    g
    • 2
    • 2
  • t

    Tolriq

    12/01/2018, 9:01 PM
    Is runBlocking{} overhead important and is it a problem to use too many in an Android app? I have quite a few place in my app that require to return an answer synchronously because I'm extending API that call me on background thread and expect answers. The underlying question, is about the fact that I should keep some non suspend / synchronous functions for those case, or the overhead is so low that it's OK to have quite a few runBlocking and allow me to keep my internals simple and only support suspend functions?
    g
    • 2
    • 14
  • p

    Pablo Costa

    12/02/2018, 12:14 PM
    Hi there! I'm just starting with Coroutines in Android and I don't even get Coroutines 101. Could someone please translate this simple Android snippet to Coroutines removing the callbacks? That would help me massively.
    StuffRepo.kt
     
    stuffDS.loadStuff (object: LoadStuffCallbacks {
        override fun onSuccess(stuff : Stuff) {
            // stuff ready
        }
    
        override fun onError() {
            // error handling
        }
    })
    StuffDS.kt
    
    fun loadStuff(callbacks : LoadStuffCallbacks) {
        val stuff = dao.loadStuff()
        if (stuff != null) callbacks.onSuccess(stuff)
        else callbacks.onError()
    }
    
    interface LoadStuffCallbacks {
        fun onSuccess(stuff : Stuff)
        fun onError()
    }
    I'm trying to replicate exactly same behaviour eliminating completely the callbacks. Is it possible to do it? What's the cleanest way of doing this? Thanks a lot!
    d
    • 2
    • 4
  • g

    gabin

    12/02/2018, 12:32 PM
    Hi there. What’s the difference between coroutine context and coroutine scope ?
    g
    • 2
    • 2
  • d

    Dmytro Danylyk

    12/03/2018, 5:08 AM
    Decided to write about several things which in my opinion you should and shouldn’t do (or at least try to avoid) when using Kotlin coroutines. Would appreciate if someone can check it and give a feedback. 😉 https://medium.com/@dmytrodanylyk/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e
    👍 5
    o
    b
    +7
    • 10
    • 70
  • e

    enleur

    12/03/2018, 12:46 PM
    should I define empty error handler to avoid this? https://pl.kotl.in/Bk5wBif1N
    g
    • 2
    • 7
  • g

    gotoOla

    12/03/2018, 4:31 PM
    anyone here that has a lot of experience with netty? We migrated a vertx+coroutine (kotlin 1.2.61-app) to ktor 1.0 and we are seeing some memory leakage. This is the visualvm images which I can’t really tell a lot from but the reason why I am asking about netty is the call-thread
    • 1
    • 3
  • d

    Diefferson

    12/03/2018, 5:44 PM
    https://medium.com/@dieffersonsantos/simple-android-cache-powered-by-coroutines-42db61306569
    r
    • 2
    • 1
  • j

    jonathan

    12/04/2018, 1:48 AM
    Hi all! I'm writing some code using coroutines and wanted to make sure I wasn't using an antipattern:
    class TSCompiler {
        private val dispatcher = Executors.newFixedThreadPool(24).asCoroutineDispatcher()
    
        public suspend fun compile(program: Any) = coroutineScope {
            launch(dispatcher) {
                // do something that takes awhile!
            }
        }
    }
    Would it be better in this case to just use the Executor directly, rather than using it as a coroutine Dispatcher?
    g
    • 2
    • 9
  • z

    zokipirlo

    12/04/2018, 8:50 AM
    I'm new to coroutines and need some help please. On coroutineContext I'm running one while loop (start function, with blocking api call) and also actor which serves to send packets (api call also). Are those api calls wait for each other or can they run in parallel? Sample code: https://goo.gl/a87Vs9
    g
    • 2
    • 6
  • r

    Razvan

    12/04/2018, 8:51 AM
    No url shorter ?
    z
    • 2
    • 2
  • a

    aaverin

    12/04/2018, 10:59 AM
    I am having a weird issue with testing Coroutines, converted to RxJava2 with
    asSingle(CommonPool)
    In a unit-test class, I have 2 different tests. Each one of them uses
    test()
    method from RxJava2 to assert the value Problem is, every time I run my tests, on of them fails, but only one of them. If I comment away one of the tests – the other one always passes. It feels like some threading issue, anybody had similar problems?
    g
    • 2
    • 6
  • m

    mingkangpan

    12/04/2018, 12:10 PM
    fun main() {
        runBlocking {
           val foo1 = withContext(IO) {
               delay(100)
               "foo1"
           }
    
           val fooDeferred = async(IO) {
                delay(100)
                "foo2"
           }
    
           val foo2 = fooDeferred.await()
           print("$foo1 and $foo2")
        }
    }
    ^ can someone tell me, what the different here between
    async(IO)
    and
    withContext(IO)
    ? only that async is deferred?
    d
    z
    g
    • 4
    • 5
  • q

    quiro

    12/04/2018, 12:34 PM
    Hey folks, I'm seeing a weird crash while using coroutines, it's happening on Samsung devices running Android 5.0 only 🤔
    Caused by java.lang.NoSuchFieldException: _decision
           at java.lang.Class.getDeclaredField(Class.java:929)
           at java.util.concurrent.atomic.AtomicIntegerFieldUpdater$AtomicIntegerFieldUpdaterImpl.(AtomicIntegerFieldUpdater.java:251)
           at java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdater.java:49)
           at kotlinx.coroutines.AbstractContinuation.(SourceFile)
           at kotlinx.coroutines.JobSupport.awaitSuspend(SourceFile:1095)
           at kotlinx.coroutines.JobSupport.awaitInternal$kotlinx_coroutines_core(SourceFile:1086)
           at kotlinx.coroutines.DeferredCoroutine.await$suspendImpl(SourceFile:99)
           at kotlinx.coroutines.DeferredCoroutine.await(SourceFile)
           at com.busuu.android.business.AppboyUtils$forceRegistration$1.invokeSuspend(SourceFile:23)
           at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(SourceFile:32)
           at kotlinx.coroutines.DispatchedTask.run(SourceFile:236)
           at android.os.Handler.handleCallback(Handler.java:739)
           at android.os.Handler.dispatchMessage(Handler.java:95)
           at android.os.Looper.loop(Looper.java:145)
           at android.app.ActivityThread.main(ActivityThread.java:5938)
           at java.lang.reflect.Method.invoke(Method.java)
           at java.lang.reflect.Method.invoke(Method.java:372)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
    t
    v
    • 3
    • 3
  • a

    andi

    12/04/2018, 1:53 PM
    Hi, we are currently rolling out an updated version of our android app, which contains an update for kotlin 1.2.71 -> 1.3.0 and coroutines 0.26.0 -> 1.0.1 . We observe unexpected crashes, that seem to somehow escape the try{}catch{} block. I described the problem and what I figured out so far here a bit more in detail: https://github.com/Kotlin/kotlinx.coroutines/issues/873 . I'm quite puzzled that some of the exceptions seem to be forwarded to the uncaught exception handler. And I'm unsure if our general approach is wrong or if this is a bug.
    t
    • 2
    • 5
  • g

    Gta

    12/04/2018, 2:57 PM
    is there an easy way to synchronize a suspend function ?
    a
    k
    g
    • 4
    • 5
  • c

    czyzby

    12/04/2018, 3:27 PM
    Is there a way to check if a certain dispatcher is in
    CoroutineContext
    ?
    • 1
    • 2
  • b

    bjartek

    12/04/2018, 5:14 PM
    Are there kotlin with coroutine alternatives to https://github.com/graphql-java/java-dataloader? Would it add value?
    s
    • 2
    • 2
  • k

    kevin.cianfarini

    12/04/2018, 6:40 PM
    does anyone know of any good talks that follows the lifecycle of a coroutine down to a kernal blocking call?
    e
    • 2
    • 1
  • d

    dewildte

    12/04/2018, 10:12 PM
    Is there anything that replaces it?
    g
    • 2
    • 2
  • n

    nulldev

    12/05/2018, 8:39 AM
    I've been trying to write a network storage access library and I have to admit the lack of suspending properties is making the syntax overly complex. I'd love to be able to do something like:
    suspend val size: Long
        get() = remoteServer.getFileSize(this)
    Instead, I'm stuck with this:
    suspend fun getSize() = remoteServer.getFileSize(this)
    So users have to do
    file.getSize()
    instead of just
    file.size
    😞 There's a discussion in the forums about this but there has been no interaction from the JetBrains team. Are there any plans to support this?
    g
    b
    • 3
    • 8
  • s

    streetsofboston

    12/05/2018, 2:39 PM
    Hello, Maybe I missed it somewhere in the documentation, but I think I can’t find a proper way to suspend a
    Job
    forever - the only way to complete the
    Job
    would be through cancellation of its scope. I used the
    delay(Long.MAX_VALUE)
    to accomplish this, but this seems wrong. Basically, the function below returns a channel that keeps sending location-updates until its enclosing scope gets cancelled.
    override fun CoroutineScope.publishLocations(): ReceiveChannel<Pair<Double, Double>> =
            Channel<Pair<Double, Double>>(capacity = Channel.CONFLATED).apply {
                val locationListener = locationListener {
                    launch { send(it.latitude to it.longitude) }
                }
    
                launch {
                    // locationListener keeps being called each time the phone's
                    // location changes, and the locations are sent to `this` Channel over and over again.
                    locationManager.requestLocationUpdates(5_000L, 0f, CRITERIA, locationListener, null)
    
                    delay(Long.MAX_VALUE) // suspend forever ...
                }.invokeOnCompletion {
                    // .. until the Job (its outer CoroutineScope) is cancelled.
    
                    // Close this Channel
                    close(it)
                    // And stop the locationManager from sending additional updates.
                    locationManager.removeUpdates(locationListener)
                }
            }
    Is there a better alternative to creating a
    Job
    that suspends forever until it’s cancelled?
    p
    d
    j
    • 4
    • 9
  • s

    Slava Glushenkov

    12/05/2018, 4:36 PM
    Why this code updates UI inside IO context and don't crash android app as expected?
    GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
     textView.text = "New Text"
    }
    g
    l
    • 3
    • 3
  • h

    hallvard

    12/05/2018, 4:58 PM
    <http://Dispatchers.IO|Dispatchers.IO>
    is a single threaded dispatcher, I believe, and the single thread in there is the IO thread. So the error is in the expectation.
    g
    • 2
    • 2
  • w

    withoutclass

    12/05/2018, 6:56 PM
    So, here is a contrived example of my problem. I am testing suspending function that returns a channel. This function sends some number of items to the channel. If I launch the coroutine for sending items on the channel using the
    coroutineScope{}
    style of
    method2
    , sending is always suspended waiting on a receiver, but
    method1
    does not get suspended(blocked). As far as I can tell, both method 1 and method2 would launch using the same dispatcher (Dispatchers.IO), and that I'm not doing anything "wrong" per se, but clearly I am given I would expect
    method1
    to not get stuck.
    Coroutine_Scope_Confusion.kt
    u
    • 2
    • 9
  • r

    rocketraman

    12/06/2018, 12:18 AM
    What's the best way to adapt lambdas that are not inline and are not suspendable? e.g.
    public inline fun CharSequence.replace(regex: Regex, noinline transform: (MatchResult) -> CharSequence): String
    from the stdlib
    g
    • 2
    • 6
  • g

    groostav

    12/06/2018, 7:50 AM
    Is there a way to print a coroutine job tree?
    v
    • 2
    • 1
  • m

    mboudraa

    12/06/2018, 2:59 PM
    Hi guys, i’m writing a
    startWith
    extension on
    ReceiveChannel
    and i was wondering which is the best way to do that. I have currently 2 implementations:
    suspend fun <A> ReceiveChannel<A>.startWith(element: A): ReceiveChannel<A> {
        val channel = Channel<A>()
        channel.offer(element)
        consumeEach { channel.send(it) }
        return channel
    }
    suspend fun <A> ReceiveChannel<A>.startWith(element: A, coroutineScope: CoroutineScope): ReceiveChannel<A> {
        return coroutineScope.produce {
            offer(element)
            this@startWith.consumeEach { this@produce.send(it) }
        }
    }
    I’m not sure what’s the difference is between the 2 and which is the best approach
    s
    m
    d
    • 4
    • 7
  • z

    zokipirlo

    12/06/2018, 3:36 PM
    If I make modifications (
    add
    ,
    remove
    ) on
    MutableList
    only in
    actor
    which runs in
    Dispatcher.MAIN
    , is it safe to call
    contains
    in other context (
    <http://Dispatcher.IO|Dispatcher.IO>
    ) or should rather check that in
    withContext(Main)
    before sending to
    actor
    ?
    b
    u
    • 3
    • 4
  • z

    zokipirlo

    12/06/2018, 3:42 PM
    Simple__non-working__example.kt
    d
    • 2
    • 4
Powered by Linen
Title
z

zokipirlo

12/06/2018, 3:42 PM
Simple__non-working__example.kt
d

dave08

12/07/2018, 3:49 AM
It looks like you can just check the not contains inside the actor, not at calling site, and it should be fine...
z

zokipirlo

12/07/2018, 7:20 AM
Yes, that's true, but don't want to "wake" actor when it's not necessary.
d

dave08

12/07/2018, 8:56 AM
It's either waking it, or using some kind of ConcurrentList, depending on the use case one might be a better choice than the other.
z

zokipirlo

12/07/2018, 10:54 AM
Thanks!
View count: 3