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

    Hexa

    05/09/2019, 9:43 PM
    Is there a better way to write this?
    runBlocking {
            coroutineScope {
                withTimeoutOrNull(10000L){ // wait time mili seconds
                    val a: Deferred<Unit> = async { s.deleteItem(xyz) }
                     val b: Deferred<Unit> = async { s.deleteItem(abc) }
    
                          launch {
                               a.await()
                                b.await()
                            }   
                     }
              }
      }
    My async calls returns Deferred<Unit> but I thought it might be better to explicitly call await() on each of them as this would force the tasks to go back in the main thread. I prefer to do it this way because I'm using AWS lambda and I read somewhere that the lambda can freeze/terminated if the tasks stays in the background thread, see https://stackoverflow.com/a/39668749
    g
    13 replies · 2 participants
  • l

    louiscad

    05/10/2019, 6:46 AM
    @Ovsyannikov Alexey @Lulu https://github.com/Kotlin/kotlinx.coroutines/issues/1080
    o
    s
    +1
    5 replies · 4 participants
  • s

    Slackbot

    05/10/2019, 11:42 PM
    This message was deleted.
    d
    2 replies · 2 participants
  • v

    voddan

    05/11/2019, 5:07 PM
    Hi! I need a bit of help understanding the IO talk on Coroutines. At this point in the talk (see the link) they have a code sample which shouldn't compile. And even if it compiled, I don't see how it would work across a
    lifecycleScope
    cancellation. What code did they have in mind? How does it work? Many thanks.

    https://youtu.be/BOHK_w09pVA?t=1719▾

    e
    g
    6 replies · 3 participants
  • s

    Sam

    05/11/2019, 9:11 PM
    I'm seeing a behavior change between kotlinx-coroutines-core:1.1.0 and kotlinx-coroutines-core:1.2.0 when testing a cancel of launched coroutine within runBlocking (runBlocking is associated with Main dispatcher and launched coroutine with Default dispatcher) 1.1.0 -> runBlocking waits for the CancellationException handling 1.2.0 -> runBlocking finishes before handling of CancellationException Is this on purpose?
    @RunWith(JUnit4::class)
    class CoroutineTest {
    
        @Test
        fun `test coroutine cancel`() {
    
            var backgroundWorkCanceled = false
    
            runBlocking {
                val scope = CoroutineScope( Dispatchers.Default + Job() )
                scope.launch {
                    try {
                        backgroundWorkCanceled = false
                        delay(3000)
                    } catch( e : CancellationException ) {
                        backgroundWorkCanceled = true
                    }
                }
                delay( 2000 )
                scope.cancel()
            }
    
            assert( backgroundWorkCanceled )
        }
    }
    l
    8 replies · 2 participants
  • v

    Viktor Qvarfordt

    05/12/2019, 9:30 PM
    If I have a channel, how can I “channel.take(5)“, ie. get a list containing the 5 items I would get if I channel.receive() 5 times?
    b
    r
    +1
    14 replies · 4 participants
  • p

    projectmoon

    05/13/2019, 10:45 AM
    i guess i could do something like:
    flow {
        while (true) { emit(x); delay(y); 
    }
    l
    8 replies · 2 participants
  • h

    Hexa

    05/13/2019, 1:05 PM
    if I have a coroutine like this:
    val  deleteJob = runBlocking {
                        withTimeoutOrNull(10000L) {
                            launch(<http://Dispatchers.IO|Dispatchers.IO>) { s.deleteItem(xyz) }
                            launch(<http://Dispatchers.IO|Dispatchers.IO>) { s.deleteItem(abc) }
                        }
                    }
    which one of these is the best way to handle a couroutine that timedout?
    if(deleteJob!!.isCancelled){
                        //do something
                    }
    // or
    if(deleteJob == null){
                        //do something
                    }
    r
    d
    6 replies · 3 participants
  • d

    dector

    05/13/2019, 1:41 PM
    In my case
    withContext(IO)
    is leaking scope through global queue after parent scope cancelation. Explicit
    withContext(coroutineContext + IO)
    works as expected. (Example in thread)
    1 reply · 1 participant
  • v

    Viktor Qvarfordt

    05/13/2019, 11:06 PM
    I’m trying to set up a minimal example that gives race conditions. Any suggestions? The best I’ve got is this https://pl.kotl.in/4yU_BS_qv but it has a quirk that I don’t understand. (Question embedded in the code snippet).
    b
    l
    9 replies · 3 participants
  • r

    ribesg

    05/14/2019, 9:24 AM
    How do you use coroutines in multiplatform tests? Do you need to
    expect
    runBlocking functions?
    g
    8 replies · 2 participants
  • r

    rook

    05/14/2019, 7:00 PM
    Can this be simplified?
    Untitled.kt
    l
    b
    +1
    24 replies · 4 participants
  • k

    krtko

    05/15/2019, 4:50 PM
    Hi one of our servers crashed last night with this error:
    Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 512k, guardsize: 0k, detached. 
    Exception in thread "HTTP-listener-11490-1" java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached 
    at java.base/java.lang.Thread.start0(Native Method)
    
    at java.base/java.lang.Thread.start(Thread.java:803) 
    at java.base/java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:937) 
    at java.base/java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:1005) 
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) 
    at java.base/java.lang.Thread.run(Thread.java:834)
    It definitely wasn't running out of memory. We do spawn a lot of coroutines, however my understanding is that shouldn't be an issue. The one place we use coroutines is:
    val pushNotificationService = this.pushNotificationService
    GlobalScope.launch {
        pushNotificationService.sendPushKit(id)
    }
    Any ideas what could be going wrong? Thanks
    b
    h
    +1
    8 replies · 4 participants
  • k

    Kulwinder Singh

    05/16/2019, 11:09 AM
    is it ok to use
    continuation.isCompleted
    i have used this and its working fine, is it ok ?
    suspend fun <T> Task<T>.await(): T {
        return suspendCancellableCoroutine { continuation ->
            addOnSuccessListener {
                if (continuation.isCompleted.not())
                    continuation.resume(it)
            }.addOnFailureListener {
                if (continuation.isCompleted.not())
                    continuation.resumeWithException(it)
            }
        }
    }
    m
    d
    +1
    5 replies · 4 participants
  • k

    Kulwinder Singh

    05/16/2019, 11:23 AM
    because i want to do nothing when Firebase callback is called twice
    l
    16 replies · 2 participants
  • r

    René

    05/16/2019, 11:36 AM
    hey guys, short question: Is there a way to define a block which is a suspend function?
    suspend fun magic(token: String) {}
    
    fun tokenMagic(refreshToken: String, work: (String)->Unit) =
            runBlocking {
                fetchToken(refreshToken)
            }?.let(work::invoke)
    
    fun example() {
        tokenMagic("42") { token ->
            magic(token) // magic should be only called from a coroutine
        }
    }
    I would like to execute "work" within a runBlocking block, so that I doesn't need to add a runBlocking statment for each usage of
    tokenMagic
    m
    4 replies · 2 participants
  • a

    Albert

    05/16/2019, 12:37 PM
    is it possible with
    joinAll
    that it throws
    CancellationException
    when this occurred in any of the
    launch {}
    ?
    r
    2 replies · 2 participants
  • r

    rook

    05/16/2019, 3:56 PM
    Are channels considered safe to use in production? I know that experimental doesn’t mean unstable, necessarily
    e
    2 replies · 2 participants
  • a

    Albert

    05/16/2019, 5:06 PM
    What is the reason behind that
    CancellationException
    does not cancel the parent
    Job
    ?
    e
    1 reply · 2 participants
  • t

    Thomas

    05/16/2019, 5:58 PM
    I have a class which is not allowed to access certain objects from multiple threads. (Similar to a database). The function
    newSingleThreadContext
    should do what I want but that creates its own thread pool, which will cause unnecessary thread switching. The doc links to issue #261. Is there an update on that issue?
    e
    5 replies · 2 participants
  • v

    Viktor Qvarfordt

    05/16/2019, 7:53 PM
    What’s the difference between
    coroutineScope
    and
    withContext(Dispatchers.Default)
    ? They both launch a suspend block with context
    Dispatchers.Default
    . Is
    withContext
    the same as
    coroutineScope { ... }.join()
    ? Is there a version of
    withContext
    that defaults to use
    Dipsatchers.Default
    similar to how
    coroutineScope
    uses
    Dispatchers.Default
    ?
    o
    e
    +1
    12 replies · 4 participants
  • v

    Viktor Qvarfordt

    05/16/2019, 9:00 PM
    What’s the easiest way of achieving parallelization for something like
    myList.map { myCpuIntensiveTask(it) }
    ?
    e
    p
    29 replies · 3 participants
  • v

    Viktor Qvarfordt

    05/16/2019, 10:24 PM
    What does it mean to declare main as
    suspend
    , ie.
    suspend fun main() { ... }
    ? Is it equivalent to having
    fun main() = runBlocking { ... }
    or something else?
    g
    e
    +2
    8 replies · 5 participants
  • j

    Joost de Vries

    05/17/2019, 9:17 AM
    Hi, I'm coming to coroutines from RxJs. And I'm looking for the equivalent of
    switchMap
    where showing search results while the user is typing. And I want to cancel all the previous requests to the server, just have the last one. In RxJs you use
    switchMap
    for that. What's the coroutine equivalent?
    p
    s
    7 replies · 3 participants
  • p

    Paul Woitaschek

    05/17/2019, 9:39 AM
    Why does this fail immediately with
    java.lang.IllegalStateException: This job has not completed yet
    ?
    kotlin
      @Test
      fun remoteConfigWorks() = runBlockingTest {
        val remoteConfig = FirebaseRemoteConfig.getInstance()
        val worked = suspendCoroutine<Boolean> { cont ->
          remoteConfig.fetch().addOnCompleteListener {
            if (it.isSuccessful) {
              cont.resume(true)
            } else {
              cont.resumeWithException(it.exception ?: AssertionError("Fetching was not succssfull"))
            }
          }
        }
        assertThat(worked).isTrue()
      }
    e
    7 replies · 2 participants
  • t

    Thomas

    05/17/2019, 4:04 PM
    Could an operator like the following be added to Flow? The debounce operator is already added, but I need one with a different timeout depending on the item. It shouldn’t be too difficult to modify the current operator to add this. I can explain my use case for this operator if needed.
    fun <T> Flow<T>.debounce(timeoutMillis: (T) -> Long): Flow<T>
    👍🏻 3
    o
    4 replies · 2 participants
  • p

    pteale

    05/18/2019, 3:58 PM
    This explains better what i am trying to achieve Say in my onStart function i call a function to get some content as soon as the activity has started.. override fun onStart() { super.onStart() contentSelectionPresenter.getAvailableContent() } And in the presenter i want to do this.. override fun getAvailableContent() : List<ContentItem> { contentSelectionView.showProgress() // Needs to run on Main thread val availableContent = contentSelectionInteractor.getAvailableContent() // needs to run on worker thread contentSelectionView.hideProgress() // Needs to run on Main thread return availableContent }
    l
    2 replies · 2 participants
  • p

    pakoito

    05/18/2019, 4:01 PM
    override fun onStart() {
           super.onStart()
    
           launch { contentSelectionPresenter.getAvailableContent() }
       }
    and whatever is within the launch block will be in a CommonPool thread and can be suspend fun
    :thread-please: 2
    l
    4 replies · 2 participants
  • p

    pteale

    05/18/2019, 4:09 PM
    private fun fibonacci() = GlobalScope.launch(Dispatchers.IO) { val result = fib(25) withContext(Dispatchers.Main) { textViewCalculating.text = result.toString() } }
    :thread-please: 2
    l
    1 reply · 2 participants
  • p

    pteale

    05/18/2019, 4:50 PM
    ok i got it working now, it appears that if you need access to the main dispatcher you have to have this line in your Gradle file
    :thread-please: 3
    m
    8 replies · 2 participants
Powered by Linen
Title
p

pteale

05/18/2019, 4:50 PM
ok i got it working now, it appears that if you need access to the main dispatcher you have to have this line in your Gradle file
:thread-please: 3
m

Matej Drobnič

05/18/2019, 4:50 PM
Yes
this is the dependency for the main dispatchers 🙂
p

pteale

05/18/2019, 4:51 PM
yeah completely missed it, been trying all sorts of shit to get this working
i just had the core dependency
i guess cause Kotlin is multiplatform not every platform is going to need access to the main thread, so makes sense its in a different repo
m

Matej Drobnič

05/18/2019, 5:14 PM
yeah, also there are multiple main dispatchers for different UI frameworks
Android being one of them
p

pteale

05/18/2019, 5:15 PM
good to know, thanks
View count: 5