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

    asad.awadia

    12/28/2018, 5:41 PM
    In kotlin it’s always to move blocking calls onto a separate dispatcher where as in go - you just launch
    go funcs
    and put whatever you want in it and let the scheduler deal with it
    a
    z
    • 3
    • 2
  • a

    Allan Wang

    12/29/2018, 3:36 AM
    When creating a method that can be cancelled, is the correct approach to use
    suspendCancellableCoroutine
    and to check for
    isCancelled
    whenever the method can be cancelled and then to throw an exception or call
    resumeWithException
    ? Is there any other way in doing this?
    g
    b
    • 3
    • 19
  • s

    Sam

    12/30/2018, 5:58 PM
    Is there a way to get the dispatcher used in runBlocking?
    d
    • 2
    • 5
  • s

    simon.vergauwen

    12/30/2018, 10:56 PM
    Is it possible to make the equivalent of an immediate executor but a
    CoroutineContext
    without depending on
    coroutines-core
    but only on what can be found in
    std-lib
    ?
    b
    d
    • 3
    • 16
  • g

    groostav

    12/30/2018, 11:40 PM
    I offer you guys a horrible, but neat, way to get at
    internal
    methods
    bad-code_kt.groovy
    😂 3
    b
    g
    • 3
    • 3
  • d

    diesieben07

    12/31/2018, 5:40 PM
    I am still not quite sure when I should be using
    fun foo(): Deferred<Foo>
    vs.
    suspend fun foo(): Foo
    . The code must execute on a specific dispatcher, so I could use
    withContext
    for the
    suspend
    version. It feels to me like
    suspend
    is the cleaner variant. Correct?
    d
    d
    +2
    • 5
    • 40
  • v

    vnsgbt

    12/31/2018, 7:41 PM
    Is it possible to use
    select
    statement in an
    actor
    ?
    :yes: 1
    b
    • 2
    • 2
  • p

    poohbar

    01/01/2019, 4:22 PM
    runBlocking
    is a bridge between the coroutine "world" and normal non-coroutine "world". Are there any other "bridges"? I am looking for
    runNonBlocking
    .
    b
    d
    • 3
    • 3
  • a

    Allan Wang

    01/01/2019, 11:44 PM
    I have the following code:
    launch {
        val cookie = web.loadLogin { refresh(it != 100) }
        L.d { "Login found" }
        FbCookie.save(cookie.id)
        web.fadeOut(onFinish = {
            profile.fadeIn()
            this@LoginActivity.launch { loadInfo(cookie) }
        })
    }
    This is inside an android activity, which implements coroutine scope on the main dispatcher. It took me a while to debug, buy if the second
    launch
    was not from the activity scope, but rather a child of the parent
    launch
    , it would never actually run. Fade out is a normal method with a callback, and loadInfo is a suspended function using
    withContext(Dispatchers.Main)
    . Why is this the case?
    g
    g
    d
    • 4
    • 12
  • b

    bdawg.io

    01/02/2019, 4:30 PM
    A thread would have done well too 🙂
    m
    • 2
    • 1
  • m

    mbonnin

    01/03/2019, 2:43 PM
    fun sampleProducer(): Channel<Int>{
            val channel = Channel<Int>(UNLIMITED)
            val thread = Thread {
                var i = 0
                while(true) {
                    channel.offer(i++)
                    Thread.sleep(1000)
                }
            }
    
            // the bellow doesn't work but it would be nice if it did
            channel.doOnCancel {
                  // terminate the thread
            }
            thread.start()
    
            return channel
        }
    
        @Test
        fun main() {
            val channel = sampleProducer()
    
            runBlocking {
                for (i in 1..5) {
                    System.out.println("received: ${channel.receive()}")
                }
                channel.cancel()
                // How can I make sure the thread is joined here or very shortly after here ?
            }
        }
    Hello everyone, I'm trying to bridge an existing library and coroutines. The library has a traditional callback API that I would like to expose as a coroutine channel. It's working well but I cannot find a way to propagate the cancellation to the library. The problem is equivalent to the snippet above. Any idea how I could achieve this ?
    d
    • 2
    • 7
  • s

    simon.vergauwen

    01/03/2019, 7:27 PM
    Can I make a
    Deferred<A>
    NonCancelable
    by wrapping and awaiting it in a
    withContext
    block like below. And how does its scope get (re)wired correctly? Snippet seems to work although I don't quite understand it.
    val def = thisWasPassedToMe()
    val result = withContext(NonCancelable) {
      def.await()
    }
    b
    g
    • 3
    • 18
  • u

    ukohlmeyer

    01/03/2019, 9:04 PM
    I’m currently looking at FoundationDB’s Flow framework. https://github.com/apple/foundationdb/tree/master/flow . One of the benefits of the
    Flow
    framework is that they can test their concurrency using a single thread and special dispatching. Could someone possibly point me at some classes that I could look at. I would like to see if I could create a similar CoroutineDispatcher/Scope to handle similar functionality
    n
    • 2
    • 5
  • g

    groostav

    01/03/2019, 9:11 PM
    I'm getting really annoyed by intelliJ's debugger's evaluate expression refusing to run
    channel.isClosedForReceive
    because
    This declaration is experimental and its usage must be marked with '@kotlinx.coroutines.InternalCoroutinesApi' or '@UseExperimental(kotlinx.coroutines.InternalCoroutinesApi::class)'
    any help?
    b
    d
    • 3
    • 9
  • j

    jw

    01/04/2019, 4:20 PM
    urls.map { async { loadUrl(it) } }.map { it.await() }
    or I think there's
    awaitAll()
    now
    s
    • 2
    • 1
  • b

    bjonnh

    01/04/2019, 10:22 PM
    is there a way to delay the start of a coroutine? I am writing a client for a REST API that has rate limits (soft, that I want to respect). So I would like to delay the start of each request if the time between the last request and current time is below the rate limit
    ✔️ 1
    a
    • 2
    • 16
  • k

    Kulwinder Singh

    01/05/2019, 8:01 AM
    Hi all, i have created
    extension
    function
    await
    to get document from firestore database. But when i'm using it like below, exception is thrown and my crashes
    Exception_is_not_caught_even_if_i_have__try_cath__block.kt
    s
    d
    l
    • 4
    • 10
  • r

    rocketraman

    01/05/2019, 3:19 PM
    I have some suspending code running inside
    withContext
    that never completes. If I remove the
    withContext
    it does run to completion. The problem seems to be my use inside the
    withContext
    block of
    async(SupervisorJob(coroutineContext[Job])) { ... }
    as described in https://github.com/Kotlin/kotlinx.coroutines/issues/763 -- if I change the call to be a straight
    async
    call, then it works fine. Either this is a bug, or I'm not understanding something...
    l
    • 2
    • 7
  • r

    Rohit Surwase

    01/07/2019, 6:58 AM
    Okay, after trying Coroutines in production I have a very noob question about Coroutines. How does Coroutines works internally? What I understood so far is it uses
    suspendable lambdas + continuation + yeild
    internally. I have also watched Exploring Coroutines in Kotlin by Venkat Subramariam several times. If Coroutines works the way it explained in the video then isn’t it like a single thread managing to execute multiple tasks depending upon the priority? Can we actually execute multiple tasks simultaneously on a single thread using Coroutines or it will be just managed by that thread? By managing I mean by using suspend + yeild, the thread will finish all tasks but time taken to finish all tasks will be combination of all individual taks. Can anyone direct me to better understand internals of Coroutines?
    c
    s
    b
    • 4
    • 9
  • m

    myanmarking

    01/07/2019, 5:44 PM
    mainScope.launch {
    
                try{
                    val attr1 = async(<http://dispatchers.IO|dispatchers.IO>) { networkUser.setUserAttrs(userId, mappedServerData.weight).blockingFirst() }catch(){} }
    z
    b
    • 3
    • 4
  • m

    myanmarking

    01/07/2019, 5:50 PM
    mainScore = CoroutineScope(dispatchers.MAIN + job)
    i have this
    :thread-please: 1
    a
    z
    u
    • 4
    • 52
  • j

    jkbbwr

    01/07/2019, 7:57 PM
    val threadPool = newSingleThreadContext("git-clone-subprocess-pool")
    
    suspend fun clone(urL: String) {
        val result = withContext(threadPool) {
            async {
                val pb = NuProcessBuilder(listOf("/bin/cat"))
                val process = pb.start()
                process.waitFor(0, TimeUnit.SECONDS)
            }
        }
        
        val exitcode = result.await()
    }
    a
    l
    • 3
    • 6
  • j

    Juan Rada

    01/08/2019, 12:27 AM
    Simple question guys, Given I have a full not blocking data pipeline, is there any case than my application would benefitc from use a coroutines dispacher with greather threads number that server number of processor (as
    DefaultDispatcher
    ) as far as I understant, my threads will be busy all the time as
    suspend
    operations will not block them so there is not benefits (in terms of pipeline throughput) from more threads, and actually throughput is expected to decrease bacause of new threads context switching.
    b
    u
    • 3
    • 3
  • w

    withoutclass

    01/08/2019, 4:04 PM
    I am building out a batch processor. I want to be able to control the number of concurrent operations using actors. I made a small test below to prove out my idea, but I want to see if there’s as simpler solution that I’ve overlooked or improvement to be made. Basically I’ll be looking to have a list of actors sized based on an ENV variable, and want to make sure that work is distributed as actors become free from processing.
    Actor_Concurrency_Test.kt
    t
    • 2
    • 1
  • b

    bdawg.io

    01/08/2019, 9:55 PM
    The name is misleading since you can’t guarantee parallel with that method. You would have to create your own thread pool to do so. You are only guaranteeing that
    n
    concurrent actors are launched
    d
    • 2
    • 3
  • a

    asad.awadia

    01/09/2019, 3:22 AM
    Is there a way to ‘demo’ the concept of ‘thread is suspended not blocked and is doing other work’?
    s
    • 2
    • 1
  • w

    withoutclass

    01/09/2019, 3:57 AM
    Print statements with thread name?
    a
    • 2
    • 3
  • j

    jw

    01/09/2019, 3:58 AM
    i'm partial to https://twitter.com/JakeWharton/status/903860259541921792
    a
    g
    • 3
    • 2
  • s

    Slackbot

    01/09/2019, 11:32 AM
    This message was deleted.
    s
    d
    d
    • 4
    • 5
  • m

    maxmello

    01/09/2019, 12:43 PM
    Hey, I want to replace Android’s
    Timer.schedule
    (one time delayed execution) with coroutines, is there a better way than just launching a coroutine and calling delay() at the beginning? With structured concurrency, it would be able to get cancelled the same way than with cancelling the Timer, right?
    a
    s
    v
    • 4
    • 5
Powered by Linen
Title
m

maxmello

01/09/2019, 12:43 PM
Hey, I want to replace Android’s
Timer.schedule
(one time delayed execution) with coroutines, is there a better way than just launching a coroutine and calling delay() at the beginning? With structured concurrency, it would be able to get cancelled the same way than with cancelling the Timer, right?
a

altavir

01/09/2019, 12:53 PM
Why do you need to use it with coroutines? Timer and coroutines are two differenc concepts and it is better not to mix them
m

maxmello

01/09/2019, 12:58 PM
I don’t want to use it with coroutines, I want to replace my Timer code with coroutine code but get the same behavior
s

streetsofboston

01/09/2019, 1:10 PM
@maxmello in short, the answer to your question is "yes" :)
v

vishna

01/09/2019, 1:11 PM
it should be fine. also never used
Timer.schedule
on Android but rather
Handler.postDelayed
m

maxmello

01/09/2019, 1:48 PM
Ok, thank you 🙂
View count: 3