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

    darkmoon_uk

    08/11/2019, 9:50 PM
    Considering creating a fork of coroutines just so that I can compile it with a later version of Gradle - it's currently on
    4.10
    which is generating an incompatibly old version of meta-data vs. say, `4.8`+ which I'm having to use to support Java 12. In the event, I can compile ok, but multi-platform modules which are dependent on coroutines fail when publishing their own metadata.
    l
    • 2
    • 4
  • s

    Shakil Karim

    08/11/2019, 10:10 PM
    Does this code can have any side effects i want to search parallelly from two source on text change ?
    Untitled.kt
    u
    • 2
    • 4
  • g

    giso

    08/12/2019, 9:05 AM
    Hi there, recently I had need for some kind of a MutableLiveData, but easily integratable with Flows and without the Android dependency. I came up with this solution, but I wonder, if there is a simpler solution. Any ideas?
    Unbenannt
    d
    g
    • 3
    • 6
  • r

    Rainer Schlonvoigt

    08/12/2019, 1:20 PM
    is there a coroutines implementation for general JVM apps, e.g. a desktop application?
    d
    l
    +2
    • 5
    • 20
  • u

    540grunkspin

    08/12/2019, 1:58 PM
    Hi oh lovely community! Is there something similar to a condition variable on coroutines?
    d
    • 2
    • 140
  • d

    Dominaezzz

    08/12/2019, 4:34 PM
    So
    Flow.conflate()
    allows emitter to never suspend but is there an operator to allow the collector to never suspend (too)?
    j
    z
    • 3
    • 6
  • r

    reline

    08/12/2019, 7:45 PM
    Is there a way to only allow experimental coroutines for tests? My gradle-fu is not exemplary.
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            kotlinOptions.freeCompilerArgs += ["-Xuse-experimental=kotlin.Experimental"]
        }
    }
    l
    m
    • 3
    • 6
  • z

    zak.taccardi

    08/12/2019, 9:28 PM
    Are there any behavior changes between
    1.2.1
    and 1.3.0-RC2` that we need to be worried about? Especially for `@ExperimentalApi`s?
    l
    d
    • 3
    • 7
  • z

    zak.taccardi

    08/12/2019, 9:30 PM
    For https://play.kotlinlang.org - can we import libraries like coroutines?
    l
    v
    • 3
    • 8
  • r

    raniejade

    08/13/2019, 4:42 AM
    Is there any reason why suspend is not supported for delegated properties? (
    suspend operator fun getValue/setValue
    )
    g
    m
    • 3
    • 25
  • c

    coder82

    08/13/2019, 10:31 AM
    I need to spawn 10 worker threads which will call blocking legacy services. I also need them to have a bounded queue from which they read from, but I don't want to go through the effort of specifying a fan out channel which they read from and then having to check the message type all the time (10 actors reading and responding pattern). Rather I'd create a custom ThreadPoolExecutor where I can make the queue bounded and submit tasks directly without having to deal with messages flowing through a channel. What do you reckon? The problem of the actor model is that I need to define a lot of data classes and check which message I get so that I know what to do in the worker, while submitting the task directly is more convenient. Unless I miss something or I get some hint here 😄
    d
    r
    • 3
    • 9
  • c

    coder82

    08/13/2019, 10:32 AM
    Another idea which pops in my mind is to use the actor model, send methods and use reflection to invoke them inside the worker, but all in all, if wonder if my thoughts are sane and if I am taking the right path. I like more the idea of submitting a task rather than a message with a "type" which leads to an implementation called by the worker @gildor @elizarov
    e
    • 2
    • 4
  • d

    Dias

    08/13/2019, 1:37 PM
    I have an api that provides 2 ways of calling a method. One returns Future (plain java future) and another one accepts callback. Which way is better to convert it to suspendable function? 1. Wrap call into withContext(Distpatcher.IO) { future.get() } 2. Wrap callback with a suspendCoroutine{ } method I prefer second option, because it looks more idiomatic, but withContext looks cleaner for a person less familiar with coroutines
    g
    • 2
    • 4
  • d

    Dias

    08/13/2019, 1:38 PM
    any other differences between these options in this particular context? apart from using different dispatchers
    g
    • 2
    • 1
  • j

    Jan Skrasek

    08/13/2019, 1:42 PM
    I'm using these extensions to convert Flow from and to LiveData. After updating to coroutines 1.3 (RC2) this seems doesn't work as intented. Is it bug or am I missing something?
    Untitled
    l
    g
    • 3
    • 5
  • a

    ahulyk

    08/13/2019, 2:09 PM
    what is the future of Coroutines after release of Project Loom?
    🔮 4
    g
    r
    +3
    • 6
    • 9
  • u

    ursus

    08/13/2019, 3:43 PM
    naively, if coroutines transform into callbacks, then those do have reference to the outer class, so it should leak, right?
    m
    v
    l
    • 4
    • 20
  • s

    Seri

    08/13/2019, 5:33 PM
    How would y’all expose subscribing to a BroadcastChannel without allowing external code to submit to it?
    z
    • 2
    • 1
  • m

    molikuner

    08/13/2019, 6:36 PM
    Hey, I'm just reading the introduction to Channels. Immediately after reading the first example with a function which creates a Chanel, I asked myself why they use an extension function for the CoroutineContext instead of just marking the function a suspend function. Original example:
    fun CoroutineScope.produceSquares(): ReceiveChannel<Int> = produce {
        for (x in 1..5) send(x * x)
    }
    What I would expect:
    suspend fun produceSquares(): ReceiveChannel<Int> = produce {
        for (x in 1..5) send(x * x)
    }
    Later in the document you can find:
    All functions that create coroutines are defined as extensions on CoroutineScope, so that we can rely on structured concurrency to make sure that we don't have lingering global coroutines in our application.
    But doesn't the
    suspend
    keyword does exactly that? It makes the current CoroutineContext implicitly available to the called function?
    o
    z
    • 3
    • 4
  • v

    voben

    08/13/2019, 8:17 PM
    I have a long running operation which I start from my
    viewModelScope
    . When the viewmodel gets destroyed before the long running operation finishes, the function println(“Hello World”) is still getting called. Wouldn’t the coroutine get cancelled and not print “Hello World” due to structured concurrency?
    viewModelScope.launch {
            doLongRunningOperation()
    }
    
    suspend fun doLongRunningOperation() = withContext(Dispatchers.Default) {
            longRunningCalculation() // Not a suspending function
            println("Hello World")
        }
    r
    l
    +4
    • 7
    • 13
  • z

    zjuhasz

    08/14/2019, 12:55 AM
    I’m trying to decide between a
    Channel
    or
    Flow
    based API for my library and I’m having a hard time. I’m looking for some info / opinions / suggestions. I posted on the forum with all the info: https://discuss.kotlinlang.org/t/deciding-between-flows-and-channels/13858
    s
    p
    +3
    • 6
    • 10
  • t

    Tuan Kiet

    08/14/2019, 7:45 AM
    Is there anyway/api to convert a Flow to LiveData?
    g
    h
    i
    • 4
    • 5
  • c

    coder82

    08/14/2019, 8:10 AM
    For calling legacy services which will block on database calls, what's the best dispatcher? is it Dispatchers.IO?
    👍 1
    :yes: 4
    g
    • 2
    • 1
  • w

    winchester044

    08/14/2019, 10:55 AM
    Hi folks, I was wondering if there is a way to cancel/stop `runBlocking`(which has an associated context) once the parent job is cancelled and the lambda is yet to start execution on the underlying dispatcher? Consider example:
    class Foo {
        val dispatcher// An android handler thread as a Coroutine Dispatcher
        val job // Parent Job
        val coroutineScope = job + dispatcher
    
        fun <T> run(block: () -> T) {
            // some prechecks
            return runBlocking(coroutinScope.coroutineContext) {
                // this runs on dispatcher
            }
        }
    
        fun shutdown() {
           // stop underlying runBlocking 
           job.cancel()
        }
    }
    Consider the handler thread is busy doing some other stuff and
    runBlocking
    is waiting for it to finish. Meanwhile
    shutdown()
    gets invoked. Is there a way to 'cancel/stop' this
    runBlocking
    call? (Without using thread interrupts, although once lambda has started execution cancellation becomes cooperative).
    m
    • 2
    • 3
  • e

    Eric Martori

    08/14/2019, 11:55 AM
    Would it be posible to include:
    suspend fun <T> Flow<T>.first() = take(1).single()
    In the flow API?
    i
    b
    • 3
    • 10
  • c

    coder82

    08/14/2019, 3:40 PM
    where do I find the bext explanation about coroutine contexts? I still struggle to inderstand them, it's really a black hole for me
    k
    d
    • 3
    • 4
  • m

    molikuner

    08/14/2019, 6:49 PM
    Does this make any sense, or has any benefit?
    fun complete(): X {
        TODO("your implementation")
    }
    suspend fun suspendComplete(): X {
        return suspendCoroutine { continuation  ->
            val result = runCatching { complete() }
            continuation.resumeWith(result)
        }
    }
    🇳🇴 7
    l
    • 2
    • 4
  • m

    Marko Mitic

    08/15/2019, 10:44 AM
    Is there an easy way to call suspend functions from Java 7? I saw some useful APIs in kotlinx-coroutines-jdk8 but that's bit too high for Android
    m
    g
    • 3
    • 3
  • t

    tjohnn

    08/15/2019, 10:53 AM
    Is there a way or an example of using Realm database with coroutines?
    m
    • 2
    • 8
  • n

    nickheitz

    08/15/2019, 11:59 AM
    Hi all. I had a play around with the ArrayBroadcastChannel today, and I'm not understanding something about cooperative cancellation.
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.CoroutineStart
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.channels.BroadcastChannel
    import kotlinx.coroutines.channels.Channel
    import kotlinx.coroutines.channels.broadcast
    import kotlinx.coroutines.delay
    import kotlinx.coroutines.isActive
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.runBlocking
    import org.junit.Test
    import kotlin.coroutines.CoroutineContext
    
    class BroadcastChannelTest : CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = <http://Dispatchers.IO|Dispatchers.IO> + Job()
    
        init {
            System.setProperty("kotlinx.coroutines.debug", "")
        }
    
        @Test
        fun broadcast() {
            val jobs = mutableListOf<Job>()
            val channel = Channel<Int>().broadcast(5, CoroutineStart.DEFAULT)
            runBlocking {
                jobs.add(createConsumer(channel))
                jobs.add(createConsumer(channel, 500, 3))
                delay(250)
    
                (0..10).forEach {
                    channel.send(it)
                    delay(200)
                }
    
                channel.send(-1)
    
                jobs.forEach {
                    it.join()
                }
            }
    
        }
    
        private fun createConsumer(channel: BroadcastChannel<Int>, delay: Int = 0, failOn: Int = 11): Job {
            return launch {
                try {
                    if (delay > 0) delay(delay.toLong())
    
                    println("creating consumer $delay")
                    val sub = channel.openSubscription()
                    for (msg in sub) {
                        if (isActive) {
                            println("$msg on ${Thread.currentThread().name}")
    
                            if (msg == -1) break
    
                            if (msg == failOn) {
                                sub.cancel()
                                throw Exception("Failing now...")
                            }
                        } else {
                            println("No longer active.")
                        }
                    }
                } finally {
                    println("Consumer done")
                }
            }
        }
    }
    in short, I want one of the channels to error out after 3 messages. GIven that all of these coroutines are (I think) running in the CoroutineScope of the class itself, the Job() at the top should lead to cooperative cancellation on an exception. However, the non erroring listener continues to completion. Any ideas?
    k
    • 2
    • 3
Powered by Linen
Title
n

nickheitz

08/15/2019, 11:59 AM
Hi all. I had a play around with the ArrayBroadcastChannel today, and I'm not understanding something about cooperative cancellation.
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.broadcast
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test
import kotlin.coroutines.CoroutineContext

class BroadcastChannelTest : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = <http://Dispatchers.IO|Dispatchers.IO> + Job()

    init {
        System.setProperty("kotlinx.coroutines.debug", "")
    }

    @Test
    fun broadcast() {
        val jobs = mutableListOf<Job>()
        val channel = Channel<Int>().broadcast(5, CoroutineStart.DEFAULT)
        runBlocking {
            jobs.add(createConsumer(channel))
            jobs.add(createConsumer(channel, 500, 3))
            delay(250)

            (0..10).forEach {
                channel.send(it)
                delay(200)
            }

            channel.send(-1)

            jobs.forEach {
                it.join()
            }
        }

    }

    private fun createConsumer(channel: BroadcastChannel<Int>, delay: Int = 0, failOn: Int = 11): Job {
        return launch {
            try {
                if (delay > 0) delay(delay.toLong())

                println("creating consumer $delay")
                val sub = channel.openSubscription()
                for (msg in sub) {
                    if (isActive) {
                        println("$msg on ${Thread.currentThread().name}")

                        if (msg == -1) break

                        if (msg == failOn) {
                            sub.cancel()
                            throw Exception("Failing now...")
                        }
                    } else {
                        println("No longer active.")
                    }
                }
            } finally {
                println("Consumer done")
            }
        }
    }
}
in short, I want one of the channels to error out after 3 messages. GIven that all of these coroutines are (I think) running in the CoroutineScope of the class itself, the Job() at the top should lead to cooperative cancellation on an exception. However, the non erroring listener continues to completion. Any ideas?
k

kingsley

08/15/2019, 12:08 PM
Quickly glancing over this. It appears that you are setting up the
coroutineContext
wrong, which might be a source of the issue You should have a:
private val job = Job()

// and then
override val coroutineContext: CoroutineContext
  get() = <http://Dispatchers.IO|Dispatchers.IO> + job

// OR
override val coroutineContext = <http://Dispatchers.IO|Dispatchers.IO> + Job()
Basically, as it is now, any coroutine you launch will be started in the context of a new parent job, since a new
<http://Dispatchers.IO|Dispatchers.IO> + Job()
is being passed down each time
n

nickheitz

08/15/2019, 7:54 PM
That makes perfect sense. I obviously misunderstood an example somewhere demonstrating how to extend CoroutineScope. Thanks.
👍 1
View count: 29