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

    Olekss

    01/27/2018, 9:54 PM
    yea... I think I understand - if I do launch/async on commonPool. then kotlin will take care of threading pool, and inside the body of the launch I can doo my socket magic?
    g
    • 2
    • 1
  • p

    Paul Woitaschek

    01/27/2018, 9:58 PM
    Injecting
    Unconfined
    in tests generally seems to be a good idea
    d
    • 2
    • 1
  • f

    Felix

    01/28/2018, 12:10 AM
    Any good sources of information about contexts, other than https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#coroutine-context?
    g
    • 2
    • 3
  • n

    nikolaymetchev

    01/28/2018, 8:04 PM
    Hello Everyone, We are using JNLP for one of our swing apps. We decided to try and add kotlin coroutines to the app and found that somehow the security settings of Java/JNLP stopped working as expected. We found all sorts of security exceptions started happening of the form
    java.security.AccessControlException: access denied ("java.util.PropertyPermission" "os.name" "read")
    . We were able to mitigate some of them by wrapping certain calls in
    AccessController.doPrivileged(...)
    , but that only pushed the problem furthe down and eventually we got NullPointerExceptions deep in our swing code
    java.lang.NullPointerException
                   at javax.swing.SizeRequirements.calculateAlignedPositions(Unknown Source)
                   at javax.swing.BoxLayout.layoutContainer(Unknown Source)
                   at java.awt.Container.layout(Unknown Source)
                   at java.awt.Container.doLayout(Unknown Source)
                   at java.awt.Container.validateTree(Unknown Source)
                   at java.awt.Container.validateTree(Unknown Source)
                   at java.awt.Container.validate(Unknown Source)
                   at java.awt.CardLayout.first(Unknown Source)
    Once we reverted the code back to using SwingWorker all those security exceptions disappeared. We are using Oracle Java 8 build 162 with kotlin 1.2.21 and coroutines swing version 0.22. Please let me know if this is a known problem and if I should bother trying to create a bug report for Jetbrains. Many thanks.
    l
    e
    • 3
    • 7
  • o

    Olekss

    01/29/2018, 7:22 PM
    Hey somehow I can't find that run {} coroutine builder doc and stuff Looking at : https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/README.md
    r
    a
    +2
    • 5
    • 8
  • d

    dave08

    01/30/2018, 3:52 AM
    @groostav It looks like all you need is to call this top level fun to create your handler instance (it's in the core lib.):
    public actual inline fun CoroutineExceptionHandler(crossinline handler: (CoroutineContext, Throwable) -> Unit): CoroutineExceptionHandler =
        object: AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler {
            override fun handleException(context: CoroutineContext, exception: Throwable) =
                handler.invoke(context, exception)
        }
    I think you were missing the CoroutineContext's element key companion object, which is what replaces your context with the default one in the lib, but the above should do the trick...
    🤔 1
    g
    • 2
    • 4
  • d

    dstarcev

    01/30/2018, 1:20 PM
    But doesn’t making assumptions about implementation lead to leaky abstractions?
    d
    • 2
    • 4
  • w

    withoutclass

    01/30/2018, 4:16 PM
    Is this pyramid of death style of receiving from channels pretty common or am I doing something silly?
    launch {
            whileSelect {
                channel.onReceive {
                    when (it) {
    // do stuff
                     }
                 }
            }
    }
    e
    • 2
    • 6
  • n

    nerses

    01/31/2018, 4:22 PM
    let me check the mockito-kotlin
    d
    • 2
    • 1
  • n

    nerses

    01/31/2018, 4:27 PM
    @gildor thanks it works with mockito-kotlin variant of any()
    o
    d
    • 3
    • 8
  • j

    johannes.lagos

    01/31/2018, 9:03 PM
    suspend fun requestSomething() {
    return suspendableCoroutine{cont-> 
    api.makeACall(object: Response{
         fun onResponse(response: Response){
           cont.resume(response)
    }
    fun onError(error: Error) {
         cont.resumeWithException(Throwable(error.message)
    }
    })
    }
    }
    And where I trigger the coroutine:
    fun aMethod(){
          launch(Android){
         try{
          requestSomething()
    }catch(e: Exception) {
      Timber.d("something went wrong")
    }
    }
    }
    g
    • 2
    • 1
  • r

    r4zzz4k

    01/31/2018, 9:11 PM
    And if I recall correctly,
    suspendableCoroutine
    is a low-level primitive, so it's reasonable to replace it with
    CompletableDeferred
    . Someone should correct me if I'm wrong, or maybe provide details on why.
    👍 1
    d
    • 2
    • 1
  • b

    bitkid

    02/01/2018, 12:24 PM
    how would i write a unit test for that? because as soon as i run this in runBlocking{} in the test doSomething() will be called on the same thread.
    e
    c
    • 3
    • 10
  • e

    elizarov

    02/01/2018, 2:57 PM
    @louiscad Experimental is not stopping us. You can post your ideas on the inspections you’d like to have to http://kotl.in/issue
    👍🏽 2
    l
    • 2
    • 1
  • d

    dstarcev

    02/01/2018, 3:37 PM
    is Mono a monad?
    e
    p
    • 3
    • 2
  • b

    bj0

    02/01/2018, 6:20 PM
    @elizarov the other day someone said
    withContext(UI) { }
    was equivalent to
    async(UI) { }.await()
    , but I am having serious problems with the latter, was that not the case?
    l
    • 2
    • 4
  • e

    elizarov

    02/02/2018, 3:40 PM
    @mansonheart In general it is all true, but a lot depends on implementation details and specifics.
    m
    • 2
    • 1
  • g

    groostav

    02/02/2018, 9:25 PM
    are there coroutine builders for
    javax.concurrent.Task
    ?
    e
    n
    • 3
    • 2
  • d

    dave08

    02/04/2018, 3:47 AM
    I don't know why, but last time I looked, but turning a callback into coroutines is in the internals KEEP doc. on github kotlinx.coroutines, not in the guide there...
    m
    g
    • 3
    • 10
  • n

    nil2l

    02/05/2018, 11:14 AM
    The subject is very nice. I think you need to add few words about Rx.
    l
    • 2
    • 1
  • d

    dave08

    02/05/2018, 4:36 PM
    Could there be any reason why the code in
    launch(UI)
    is not reached at all after it was run? And the screen in Android device goes black... I tried putting logs there, reducing it to doing almost nothing (only
    Log
    ...)... the screen just blanks out
    m
    g
    e
    • 4
    • 9
  • e

    elizarov

    02/07/2018, 6:46 PM
    @bj0 we'll have a new release of
    kotlinx.coroutines
    when Kotlin 1.2.30 is out. The plan is to have
    isActive
    extension on
    CoroutineContext
    , so that you can use
    coroutineContext.isActive
    . The open question is whether
    CoroutineScope
    shall be completely deprecated and slated for removal or should we leave
    isActive
    "shortcut" in the
    CoroutineScope
    ?
    l
    • 2
    • 1
  • n

    nerses

    02/08/2018, 1:40 PM
    Hi, I am not getting how Exception propagation is happening. Here is a pseudo code and test
    fun populate(hotels: List<Hotel>) {
            
            val context = newFixedThreadPoolContext(threadpoolCoreSize, "thread-geo")
    
              context.use { c ->
                    val jobs = hotels.map { hotel ->
                        launch(c) {
                            repo.suspendableFun()
                        }
                    }
                    runBlocking(c) {
                        jobs.forEach({ it.join() })
                    }
                }
      }
    and
    @Test(expectedExceptions = [RuntimeException::class])
        fun `populate should throw exceptionIn`() = runBlocking {
            //and
            given(repo.suspendableFun()).willThrow(RuntimeException(""))
    
            //when
            victim.populate(hotelList())
    
            //then
            //The exception is thrown
        }
    i
    • 2
    • 9
  • b

    bazted

    02/09/2018, 11:16 AM
    Hello, I may have strange question, but how can I create some
    onComplete
    like listener for ReceiveChannel. for now I have
    fun <T> ReceiveChannel<T>.onComplete(action: suspend () -> Unit): ReceiveChannel<T> {
        launch(Unconfined) {
            consumeEach { }
            action()
        }
        return this
    }
    e
    • 2
    • 1
  • g

    gaetan

    02/09/2018, 1:31 PM
    Sorry to mention you @elizarov but don’t you have an idea of how to do that?
    e
    i
    • 3
    • 11
  • j

    jimn

    02/09/2018, 9:59 PM
    i have initializers in a couroutine which are happening apparently within clinit (gsonbuilder) and im getting strange error. Caused by: java.io.FileNotFoundException: null\lib\tzdb.dat (The system cannot find the path specified)
    e
    • 2
    • 2
  • l

    louiscad

    02/10/2018, 3:21 PM
    I know I can make a full coroutines Activity where the
    onCreate(…)
    would be a
    suspend fun
    so I can right away use
    withContext(IO)
    for things like SharedPreferences access, but should I? Should I use coroutines everywhere so whenever I need to access even small things in storage that may be cached in memory, I can just do it in a non UI thread coroutineContext and suspend when I can?
    e
    s
    • 3
    • 5
  • l

    louiscad

    02/10/2018, 4:38 PM
    @luciofm I was thinking about cancelling the job when the lifecycle state is no longer valid, e.g. cancel
    onResume()
    coroutine when
    onPause()
    is called.
    :thread-please: 1
    l
    • 2
    • 3
  • m

    mansonheart

    02/10/2018, 6:46 PM
    How does
    delay()
    work? A comment in source code (method
    scheduleResumeAfterDelay
    ) says: This implementation is supposed to use dispatcher's native ability for scheduled execution in its thread(s). It means that the method interacts with the thread scheduler to put the current thread into a wait state for the required interval? (like Thread.sleep() https://www.javamex.com/tutorials/threads/sleep.shtml) Or what kind of native ability are we talking about?
    l
    s
    e
    • 4
    • 6
  • l

    louiscad

    02/11/2018, 10:33 AM
    New question: Does
    withContext
    handles cancellation before and after running its lambda?
    j
    • 2
    • 3
Powered by Linen
Title
l

louiscad

02/11/2018, 10:33 AM
New question: Does
withContext
handles cancellation before and after running its lambda?
j

Jonathan

02/13/2018, 4:56 PM
doc states:
By default, the coroutine is immediately scheduled for execution and can be cancelled while it is waiting to be executed and it can be cancelled while the result is scheduled to be processed by the invoker context
my understanding is the correct answer to your question is "before and after"
l

louiscad

02/13/2018, 6:15 PM
Thanks @Jonathan, this confirms my intuition. Was it in
withContext
doc (which I would have shamefully overlooked), or somewhere else (in this case, could you link it?)?
j

Jonathan

02/13/2018, 8:57 PM
Yes it was in the
withContext
doc. https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-context.html
👍🏽 1
View count: 2