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

    jw

    07/21/2018, 3:12 AM
    i'm really interested in how the coroutine model will translate into that as well. i'm glad others are taking the plunge. i'm trying to follow along on issues and the like, but not getting my feet wet just yet.
    s
    • 2
    • 5
  • v

    v0ldem0rt

    07/21/2018, 9:36 PM
    Using ConcurrentHashMap can block a thread coroutine is running on
    v
    g
    • 3
    • 6
  • g

    groostav

    07/23/2018, 7:51 AM
    also, does anybody else things its strange that
    select {}
    will simply abandon your coroutine?
    @Test fun `using an empty select clause just abandons you`() = runBlocking {
    
            val producer = produce<String> {
                select<String> {
                    val x = 4;
                }
    
                val y = 4;
            }
    
            val result = producer.receiveOrNull()
    
            val z = 4;
        }
    never completes
    e
    • 2
    • 7
  • v

    v0ldem0rt

    07/23/2018, 3:38 PM
    If I've created a threadpool using
    newFixedThreadPoolContext
    then will coroutines jump between threads like
    Unconfined
    ?
    g
    m
    • 3
    • 2
  • r

    rocketraman

    07/23/2018, 6:25 PM
    What is the state of Exception stack recovery on resume with coroutines? On 1.2.51, 0.23.4, I'm seeing the first line of my stack as
    doResume
    within a class without a line number e.g.
    at com.MyClass$withFoo$1.doResume(MyClass.kt) ~[classes/:?]
    i
    • 2
    • 1
  • g

    groostav

    07/25/2018, 6:28 AM
    would appreciate any feedback
    n
    • 2
    • 3
  • b

    bj0

    07/25/2018, 11:23 PM
    or does this cover that: https://github.com/Kotlin/kotlinx.coroutines/issues/280
    e
    • 2
    • 3
  • w

    winteryoung

    07/26/2018, 1:03 PM
    This is an excerpt from Mutex.kt. I think
    cont.initCancellability()
    should be placed after
    removeXXX
    . Because if the coroutine was cancelled right after the init call, the waiter won't be removed.
    e
    • 2
    • 4
  • d

    dharrigan

    07/26/2018, 6:58 PM
    I have a question about coroutines (in combination with android apis that have callbacks). Would this, or #android be the appropriate channel?
    w
    • 2
    • 2
  • k

    kevinherron

    07/27/2018, 3:36 AM
    yes, just wondering if it will be merged in time for the 1.3 release. I guess I could have phrased that better.
    e
    • 2
    • 2
  • g

    gildor

    07/27/2018, 6:13 AM
    Hmm, interesting, I see But also you can just call suspend function that can cache result under the hood
    v
    • 2
    • 1
  • u

    uhe

    07/27/2018, 2:25 PM
    so after upgrading to 0.24.0 my unit tests started failing due to
    java.lang.RuntimeException: Method myLooper in android.os.Looper not mocked. See <http://g.co/androidstudio/not-mocked> for details.
    
    	at android.os.Looper.myLooper(Looper.java)
    	at kotlinx.coroutines.experimental.android.MainLooperChecker.checkRunBlocking(HandlerContext.kt:124)
    The tests are plain JVM unit tests and use
    runBlocking
    to test presenters
    e
    • 2
    • 2
  • w

    wakingrufus

    07/27/2018, 8:10 PM
    if i have an
    async {
         while(isActive){
             ....
         }
        return "something"
    }
    how can I cancel it so that I can call
    await
    without getting a cancellation exception?
    d
    • 2
    • 6
  • s

    spierce7

    07/27/2018, 10:22 PM
    In case anyone missed the planned cold-streams work explanation: https://github.com/Kotlin/kotlinx.coroutines/issues/254#issuecomment-408379789
    👍 2
    u
    • 2
    • 3
  • d

    dharrigan

    07/28/2018, 2:13 PM
    Very clear 🙂
    r
    • 2
    • 1
  • s

    svenjacobs

    07/30/2018, 11:38 AM
    Hi all, I'm looking for a simple coroutine-based event bus. I found this implementation https://gist.github.com/takahirom/f2dbcc3053adfd87ac7e321d95a23021 however I have an issue with it. It uses
    ConflatedBroadcastChannel
    which keeps the last sent item and delivers it to new subscribers in
    openSubscription()
    . I'm looking for an event bus implementation that does not cache items. So if an event is send but there are no active subscriptions the bus should just drop the event. Unfortunately there doesn't seem to be a default implementation of
    BroadcastChannel
    with these characteristics. Has anyone an idea how to implement a simple non-caching event bus?
    l
    • 2
    • 8
  • r

    rdhruva

    07/30/2018, 5:12 PM
    hi, anyone have a good guide / blog posts or hints on writing a custom
    CoroutineContext
    ? Context: In my android app, I have a “god” object that handles all the network api calls and responses (using callbacks), and has its own lifecycle of sorts: I’m trying to write a
    CoroutineContext
    that will allow me to write coroutines that dispatch to the
    DefaultDispatcher
    but are aware of the lifecycle of this god object
    😱 1
    🙈 2
    g
    • 2
    • 1
  • j

    Jonathan Walsh

    07/31/2018, 5:07 PM
    I’m having some issues using
    asCompletableFuture
    . It seems to hang if my coroutine throws an exception.
    class CompletableFutureTest {
        @Test
        fun testFailAsCompletableFuture() {
    
            val executeJob = async {
                fail("Test failed predictably")
            }
    
            val future = executeJob.asCompletableFuture()
            println("### asCompletableFuture")
            future.get()
            println("### Execute job completed!")
        }
    }
    I get this stacktrace in the log
    Exception in thread "ForkJoinPool.commonPool-worker-1 @coroutine#1" kotlinx.coroutines.experimental.CompletionHandlerException: Exception in completion handler InvokeOnCompletion[InvokeOnCompletion@377acc75] for "coroutine#1":DeferredCoroutine{CompletedExceptionally}@685fc50a
    	at kotlinx.coroutines.experimental.JobSupport.completeUpdateState(JobSupport.kt:226)
    	at kotlinx.coroutines.experimental.JobSupport.updateState(JobSupport.kt:157)
    	at kotlinx.coroutines.experimental.JobSupport.makeCompletingInternal(JobSupport.kt:568)
    	at kotlinx.coroutines.experimental.JobSupport.makeCompletingOnce$kotlinx_coroutines_core(JobSupport.kt:552)
    	at kotlinx.coroutines.experimental.AbstractCoroutine.resumeWithException(AbstractCoroutine.kt:110)
    	at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:41)
    	at kotlinx.coroutines.experimental.DispatchedTask$DefaultImpls.run(Dispatched.kt:150)
    	at kotlinx.coroutines.experimental.DispatchedContinuation.run(Dispatched.kt:14)
    	at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402)
    	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
    Caused by: java.lang.AssertionError: Test failed predictably
    	at org.junit.Assert.fail(Assert.java:88)
    	at kotlin.test.junit.JUnitAsserter.fail(JUnitSupport.kt:56)
    	at kotlin.test.AssertionsKt__AssertionsKt.fail(Assertions.kt:89)
    	at kotlin.test.AssertionsKt.fail(Unknown Source)
    	at completable.future.test.CompletableFutureTest$testFailAsCompletableFuture$executeJob$1.doResume(CompletableFutureTest.kt:14)
    	at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:42)
    	... 7 more
    v
    • 2
    • 2
  • d

    dharrigan

    07/31/2018, 8:09 PM
    Since runBlocking is now disallowed on Android (since 0.24.0), anyone got any experience on alternative mechanisms that can be used to bridge between the blocking world and the non-blocking world?
    b
    • 2
    • 1
  • d

    dharrigan

    07/31/2018, 8:17 PM
    🙂 No worries, I appreciate your responses anyway, since if I come to use activities (in the future) - I have an answer! 🙂
    w
    b
    • 3
    • 5
  • a

    asad.awadia

    07/31/2018, 10:48 PM
    Anybody work with go goroutines? I have a few questions about concepts and how similar they are to kotlin coroutines
    l
    v
    d
    • 4
    • 19
  • u

    uhe

    08/02/2018, 8:40 AM
    after upgrading to Kotlin 1.2.60 I get weird compiler errors regarding `@RestrictsSuspension`:
    @RestrictsSuspension
        class Foo() {
            suspend fun bar() = Unit
        }
    
        // ERROR: Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope
        fun yUnoWork() = runBlocking { Foo().bar() }
    i
    • 2
    • 3
  • w

    winteryoung

    08/03/2018, 2:09 AM
    This hasn't got an effective answer. I'm getting the same problem. Anyone can help?
    e
    • 2
    • 3
  • w

    winteryoung

    08/03/2018, 2:14 AM
    Another request. I found LockFreeLinkedListHead/Node very useful in implementing custom locks. But these classes are currently in the internal package. Can we make it a public API?
    e
    • 2
    • 1
  • j

    jw

    08/05/2018, 8:40 PM
    No
    s
    • 2
    • 1
  • l

    louiscad

    08/05/2018, 10:42 PM
    Hi, I'm working on an open source Android library that makes Camera2 API actually usable (with readable code) thanks to coroutines, and there are some places where it takes a
    Handler?
    . Since coroutines already have the concept of dispatcher, there's a kind of concept duplication (although
    Handler
    is single threaded, unlike `CoroutineDispatcher`s). I'd like to avoid this leaking into the API of my library as method parameters, so I'm thinking about putting the
    Handler
    into the
    CoroutineContext
    so it can be retrieved by the library. Do you think it's a good usage of
    CoroutineContext
    ThreadLocal-like abilities?
    :thread-please: 1
    g
    v
    • 3
    • 5
  • m

    mp

    08/05/2018, 10:53 PM
    Are there established ways to convert various flavors of future (beyond
    CompletionStage.asDeferred()
    ) into
    Deferred
    for use in
    suspend
    functions? If not, I can always adapt code from
    asDeferred
    , but if there’s something supported out there, might as well use it
    g
    • 2
    • 4
  • s

    ske

    08/06/2018, 4:17 PM
    Is there a way to stop Kotlin from ruining stack traces when suspending?
    :trollface: 1
    🚧 1
    v
    • 2
    • 9
  • a

    amrelmasry

    08/06/2018, 7:35 PM
    Can anyone please explain what
    yield()
    is doing?
    @Test
        fun testLaunchAndYieldJoin() = runTest {
            expect(1)
            val job = launch(coroutineContext) {
                expect(3)
                yield()
                expect(4)
            }
            expect(2)
            assertTrue(job.isActive && !job.isCompleted)
            job.join()
            assertTrue(!job.isActive && job.isCompleted)
            finish(5)
        }
    w
    g
    • 3
    • 11
  • a

    Alowaniak

    08/06/2018, 9:59 PM
    message has been deleted
    d
    j
    +2
    • 5
    • 8
Powered by Linen
Title
a

Alowaniak

08/06/2018, 9:59 PM
message has been deleted
d

diesieben07

08/06/2018, 10:00 PM
val a: Deferred<Boolean> = TODO()
val b: Deferred<Boolean> = TODO()
val result = async {
    a.await() || b.await()
}
a

Alowaniak

08/06/2018, 10:07 PM
won't this wait for a first, then b though? Instead of short circuiting when b returns true before a?
d

diesieben07

08/06/2018, 10:12 PM
oh, that is true. you would have to do two async's then
Actually, that is not true. Not quite sure how you would do it with short-circuit tbh
j

jw

08/06/2018, 10:40 PM
you need a
select
g

groostav

08/07/2018, 1:46 AM
@diesieben07 to elaborate on what jake said: https://gist.github.com/Groostav/ac3f4090199153b2db94fa2016b20852
I think one of the problems with short circuiting as such is that
Deferreds
are eager by default, in other words, when you write
async
, we dont create a lazy coroutine by default. In other words, by expressing
right
as a Deferred, its already running, so you've already lost the point of short-circuiting typically. If you chose to express it as a
suspend () -> Boolean
though...
b

bdawg.io

08/07/2018, 5:41 PM
If you consider
val a: Boolean
val b: Boolean
a || b
,
a
is evaluated first and THEN
b
, which the results happen to be available already so it can immediately evaluate. It seems inconsistent that a
Deferred
variant would potentially evaluate
b
first instead of awaiting the value of
a
View count: 4