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

    Luke Rohde

    11/08/2019, 5:08 PM
    there isn’t a coroutines standard lib function for retries is there?
    s
    g
    d
    • 4
    • 4
  • j

    jeff

    11/08/2019, 5:58 PM
    Is there a way to 'cache'/share a Flow? E.g. I have
    flow { expensiveNetworkOperation() }
    and I want to collect that flow repeatedly. What's the best way to prevent duplicating the expensiveNetworkOperation() call?
    n
    o
    s
    • 4
    • 5
  • b

    bholota

    11/09/2019, 10:45 PM
    Hey, I was reading some androiddev stuff on reddit and i've stumbled upon Vasiliy's rant on coroutines: https://www.techyourchance.com/kotlin-coroutines-in-complex-scenarios/. Apart from doing weird points he mention blocking issue - i've investigated his code but I need some help with understanding the reason. For me it looks like deadlock - dispatcher tries to dispatch coroutine on already locked (BlockingQueue) thread and we're ending up with Producers or Consumers only without chance to dispatch other type of worker. Am I right?
    f
    o
    • 3
    • 20
  • u

    ursus

    11/09/2019, 10:58 PM
    Hi, how would one migrate Single.fromCallable { } into coroutines? Should I just leave it as regular blocking function?
    b
    o
    g
    • 4
    • 63
  • s

    sujin

    11/10/2019, 10:06 AM
    How to transform data using coroutines in each repository layer? Something like we do in RxJava using map or flatmap. For example, using flatmap in remote layer for converting necessary changes and use that output in data layer
    g
    r
    • 3
    • 12
  • j

    janvladimirmostert

    11/10/2019, 5:25 PM
    CompletableFuture.await()
    , how much overhead does
    await()
    add in the scenario where the
    CompletableFuture
    is not yet done?
    public suspend fun <T> CompletionStage<T>.await(): T {
        // fast path when CompletableFuture is already done (does not suspend)
        if (this is Future<*> && isDone()) {
            ...
        }
    
        // slow path -- suspend
        return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
            val consumer = ContinuationConsumer(cont)
            whenComplete(consumer)
            cont.invokeOnCancellation {
                // mayInterruptIfRunning is not used
                (this as? CompletableFuture<T>)?.cancel(false)
                consumer.cont = null // shall clear reference to continuation to aid GC
            }
        }
    }
    Is the overhead just extra class instances being created or is there more happening?
    o
    • 2
    • 2
  • u

    ursus

    11/10/2019, 7:09 PM
    How do you guys handle coroutines in android, which want to outlive the viewmodel scope? should repository or whatever does the couroutine have its scope, and be transparent to the viewmodel or should that scope be passed into the viewmodel and viewmodel launches the coroutine into that scope?
    o
    k
    g
    • 4
    • 61
  • e

    elaborate tissue

    11/11/2019, 2:47 AM
    withContext(Dispatchers.IO) { }, would you guys say this is similar to the coroutine saying "hey i'm about to perform some slow task, does anyone else speedier want to jump in before me?"
    o
    v
    • 3
    • 7
  • m

    Mark

    11/11/2019, 6:40 AM
    Anyone have any experience writing to Android’s AudioTrack using coroutines? If so, any tips/gotchas etc? I’m thinking particularly in terms of managing buffering (because want to calculate PCM data lazily since it could be very large) and managing playback state.
    t
    • 2
    • 1
  • t

    trathschlag

    11/11/2019, 9:53 AM
    Is there a coroutine equvalent for
    lazy
    ? I'm not looking for
    async
    . All I want is execution in the current coroutine, if the value was not yet computed.
    m
    j
    b
    • 4
    • 8
  • g

    ghedeon

    11/11/2019, 4:17 PM
    Trying to invoke a coroutine from Java, for some legacy code. This doesn't start it so far, do I miss something?
    CoroutineScope scope = ViewModelKt.getViewModelScope(this);
            BuildersKt.launch(scope, scope.getCoroutineContext(), CoroutineStart.DEFAULT,
                    (_scope, continuation) -> signUp.invoke(params, continuation)
            );
    z
    • 2
    • 2
  • a

    Animesh Sahu

    11/12/2019, 4:10 PM
    somebody know some inbuilt function similar to apply() which can execute suspendable block of code?
    s
    t
    • 3
    • 8
  • e

    elaborate tissue

    11/12/2019, 5:18 PM
    Is it possible to subclass a KClass from java that contains a suspend function? When I try I get given a Continuation object, that I have no idea how to use
    g
    • 2
    • 1
  • u

    ursus

    11/12/2019, 6:03 PM
    Hi, if I for loops async { }, is there a guarantee of order of them starting to run? I have a semaphore inside them, but it seems race-y
    o
    z
    • 3
    • 11
  • u

    ursus

    11/12/2019, 6:28 PM
    Can I conditionally park a coroutine, and resume it after some signal?
    o
    • 2
    • 1
  • a

    aerb

    11/12/2019, 7:12 PM
    Is there anyway to know if a Job has been cancelled other than checking
    isActive
    or having a CancellationException thrown?
    o
    z
    • 3
    • 26
  • u

    ursus

    11/12/2019, 7:12 PM
    Ehm, I might be stupid -- how can I await on List<Deferred> ? deferreds.forEach { it.await() } seems to make it sequential
    o
    w
    • 3
    • 5
  • j

    julioyg

    11/13/2019, 10:45 AM
    Good morning (for some at least i guess 😅 ) I'm starting to use flows and I wonder how can i specify the thread the function I pass onto
    collect
    is executed. I'm trying:
    launch(UI) {
      flow.collect {
        // i was hoping this was executed in UI
      }
    should that be running in the UI Dispatcher?
    n
    s
    t
    • 4
    • 14
  • m

    mzgreen

    11/13/2019, 11:07 AM
    In
    CoroutineScope(Dispatchers.Main + job)
    the order of contexts doesn’t matter and it’s the same if I call
    CoroutineScope(job + Dispatchers.Main)
    , right?
    s
    • 2
    • 2
  • a

    Alexjok

    11/13/2019, 12:08 PM
    Hello! I have a problem with simple flow sample:
    flowOf(1,2,3).collect { value -> println(value)  }
    It doesn't compile cause: Type mismatch: Required: FlowCollector<Int> found (Nothing) -> Unit What i doing wrong?
    s
    • 2
    • 2
  • j

    Justin

    11/14/2019, 5:50 AM
    So if actors are obsolete, what should I be using in their place? Or am I missing something?
    o
    p
    +2
    • 5
    • 9
  • a

    Animesh Sahu

    11/15/2019, 4:53 AM
    What's the best way to run a coroutine environment application in jvm? Basic structure of application that i want is as shown
    fun main() {
        Foo()
    }
    
    class Foo {
        val bar = Bar()
    }
    
    class Bar() {
        // perform some long running tasks with some part dependent on foo
    }
    Case 1:
    fun main = runBlocking { //this: CoroutineScope
        Foo(this)
    }
    class Foo(scope: CoroutineScope): CoroutineScope by scope {
        val bar = Bar(this)
    }
    
    class Bar(val foo: Foo): CoroutineScope by foo {
    }
    Case 2:
    fun main = runBlocking { //this: CoroutineScope
        Foo(this)
    }
    class Foo(scope: CoroutineScope): CoroutineScope {
        override val coroutineContext = scope.coroutineContext
        val bar = Bar(this)
    }
    
    class Bar(val foo: Foo): CoroutineScope {
        override val coroutineContext = foo.coroutineContext
    }
    Case 3:
    fun main() {
        //just dont start coroutine here
        Foo()
    }
    
    class Foo: CoroutineScope {
        override val coroutineContext = Dispatchers.Default
        val bar = Bar(this)
    }
    
    class Bar(foo: Foo): CoroutineScope {
        override val coroutineContext = Dispatchers.Default
    }
    Or if there is a better way to create a coroutine driven application?
    b
    z
    d
    • 4
    • 14
  • a

    Animesh Sahu

    11/15/2019, 5:10 AM
    Also what is difference between Dispatchers.IO and Dispatchers.Default
    fun main() = runBlocking<Unit> {
    	launch(Dispatchers.Default) {
    		println("Default               : I'm working in thread ${Thread.currentThread().name}")
    	}
    	launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    		println("IO                    : I'm working in thread ${Thread.currentThread().name}")
    	}
    }
    Output:
    Default               : I'm working in thread DefaultDispatcher-worker-1
    IO                    : I'm working in thread DefaultDispatcher-worker-3
    b
    e
    • 3
    • 10
  • l

    louiscad

    11/15/2019, 3:47 PM
    Is there a way to read/write a file without blocking a thread at all that I could put in a simple extension function? Right now, the easiest way I know is blocking a thread from
    <http://Dispatchers.IO|Dispatchers.IO>
    and using
    readText()
    or
    readBytes()
    , but this still blocks a thread while we are waiting for storage and not the CPU.
    d
    p
    +6
    • 9
    • 28
  • b

    breandan

    11/15/2019, 7:09 PM
    Does anyone else have a use case for multi-shot continuations?
    b
    s
    +3
    • 6
    • 16
  • m

    Mark

    11/16/2019, 7:03 AM
    Idiomatic way to lazily instantiate AND initialise a class that should only ever be instantiated and initialised max once. At the moment I have:
    private lateinit var deferredFactory: Deferred<MyFactory>
    
    suspend fun getMyFactory(): MyFactory = withContext(Dispatchers.Main) {
        if (::deferredFactory.isInitialized) {
            return@withContext deferredFactory.await()
        }
        val deferred = CompletableDeferred<MyFactory>().apply {
            deferredFactory = this
        }
        createFactory().also {
            deferred.complete(it)
        }
    }
    
    private suspend fun createFactory() = withContext(Dispatchers.Default) {
        // slow stuff
    }
    
    === UPDATE ===
    After all the comments, this is what we came up with:
    
    private val deferredFactory = GlobalScope.async(start = CoroutineStart.LAZY) {
        createFactory()
    }
    
    suspend fun getFactoryOrNull() =
        try {
            deferredFactory.await()
        } catch (e: Exception) {
            //loge("unable to create factory", e)
            null
        }
    o
    a
    +3
    • 6
    • 82
  • u

    uli

    11/16/2019, 2:37 PM
    What is the best dispatcher for file io? My understanding is that the io dispatcher strongly scales (creates unbounded? amount of threads) due to the assumption that io will mostly sleep. The default dispatcher is ment for CPU bound work and therefore limits it's thread utilization to the number of CPUs (-1) to not schedule more work than the CPUs can handle. Now file io puts a CPU in io wait state. Should this be considered CPU bound and hence the default dispatcher should be used?
    a
    • 2
    • 2
  • s

    SrSouza

    11/16/2019, 4:34 PM
    Hi guys, what is the easy way to have something like ConcurrencyHashMap in Kotlin Multiplatform with Coroutines multiplatform? I'm building a library that the functions changes the values of a Map, removing, searching and adding values, and anyone that calls this functions can call in different threads(or workers in native if I'm correctly)
    k
    • 2
    • 2
  • h

    Hexa

    11/17/2019, 10:16 AM
    val one = GlobalScope.async(start = CoroutineStart.LAZY) { A() }
        val two = GlobalScope.async(start = CoroutineStart.LAZY) { B() }
    
        one.start()
        Thread.sleep(1000)
        two.start()
    is there a better way to wait for
    one
    to start first before starting
    two
    without using Thread.sleep in between?
    s
    u
    +3
    • 6
    • 10
  • a

    Animesh Sahu

    11/18/2019, 3:34 PM
    are coroutines thread safe, like should i use atomic types?
    g
    z
    s
    • 4
    • 13
Powered by Linen
Title
a

Animesh Sahu

11/18/2019, 3:34 PM
are coroutines thread safe, like should i use atomic types?
g

gildor

11/18/2019, 3:38 PM
It depends what exactly you are doing
a

Animesh Sahu

11/18/2019, 3:45 PM
I'm implementing/typing to achieve lateinit vals using delegation, since the call is blocking i dont want to block thread while instantiating object, using IO dispatcher to set the val, and ensuring no override can be done.
private val value= AtomicReference<T>()
if (!value.compareAndSet(null, value)) {...}
vs
private var value: T? = null
if (this.value != null) {...}
in case of dispatching to io pool, should atomic references be used
Ohh wow lol https://discuss.kotlinlang.org/t/idiomatic-way-for-asynchronous-construction/14560 fake constructors are great xd, i would just do all async work in there before initializing the object
z

zak.taccardi

11/18/2019, 5:23 PM
a coroutine is thread safe
but if you access state from outside that coroutine and that state isn’t thread safe, then you will have a race condition
you can think of thread safety as something being thread safe based on the context it’s being written to and read from
AtomicBoolean
is thread safe by itself, but use it in an object that isn’t thread safe and your
Boolean
is no longer thread safe
coroutines are no different
but using a coroutine + message passing is an awesome way to achieve thread safety. https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#actors
s

SrSouza

11/18/2019, 9:40 PM
Sad that Actors is not multiplataform
z

zak.taccardi

11/18/2019, 10:35 PM
Why aren't they?
You can replicate an actor with a channel that you just launch immediately and maintain a reference to it
View count: 3