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

    Vincent Williams

    07/29/2020, 10:07 PM
    Are these two code snippets equivalent?
    val job = SupervisorJob()
    val lifecycleScope = CoroutineScope(Dispatchers.Main + job)
    
    lifecycleScope.launch { }
    val job = SupervisorJob()
    val lifecycleScope = CoroutineScope(job)
    
    lifecycleScope.launch(Dispatchers.Main) { }
    o
    7 replies · 2 participants
  • c

    camdenorrb

    07/30/2020, 12:07 AM
    I'm trying to use Channels to make a DirectByteBufferPool but I have been experiencing a lot of issues ByteBufferPool: https://github.com/camdenorrb/Netlius/blob/master/src/main/kotlin/me/camdenorrb/netlius/net/DirectByteBufferPool.kt Testing file: https://github.com/camdenorrb/Netlius/blob/master/src/main/kotlin/me/camdenorrb/netlius/Main.kt It refuses to go higher than the specified BUFFER_COUNT when I would ideally like to support thousands of clients at once. For some reason Channel doesn't seem to be queuing up all the receivers like expected or something. I'm not fully sure on what is exactly wrong with this one and I have been struggling to do anything about it. Any help is much appreciated.
    o
    j
    52 replies · 3 participants
  • d

    Darren Gu

    07/30/2020, 7:00 PM
    fun main() = runBlocking {
        test()
    }
    
    suspend fun test() {
        val job = coroutineScope {
            launch {
                delay(5000)
            }
        }
        println("job = $job")
    }
    I need to have a reference to the job when it’s running. But the print doesn’t seem to execute until 5 sec later. What would be the correct way to achieve this?
    f
    t
    +1
    22 replies · 4 participants
  • s

    Santiago Laport

    07/30/2020, 9:53 PM
    Hello guys, first of all my apologies for my bad English :) I have an exception in my code, probably I need to do it in a better way but I dont know how yet. I want to call a bunch of listeners of a library as a sequence, so I added a continuation in every callback The code is more less like this:
    fun method(){
        viewModelScope.launch {
            val result1 = getSomeData1()
            val result2 = getSomeData2()
            val result3=  getSomeData3()
            ...
        }
    }
    
    suspend fun getSomeData1() : String? = suspendCoroutine { continuation ->
        someInstance.addListener(SomeListener {
                    continuation.resume(data)
                })
    }
    ...
    First time works well, but sometimes I need to execute again and I get the next exception:
    IllegalStateException : Already resumed
    this occurs in in the
    continuation.resume
    o
    k
    4 replies · 3 participants
  • r

    rkeazor

    07/31/2020, 3:08 AM
    Is sharedFlow, out on RC yet?
    z
    a
    3 replies · 3 participants
  • c

    Colton Idle

    07/31/2020, 7:50 AM
    Upgraded to kotlin 1.4-rc but I'm getting file wide red lines in intellij. As a last shot I want to update
    org.jetbrains.kotlinx:kotlinx-coroutines-core
    but I don't see an 1.4-rc artifact on jfrog. Am I missing something?
    c
    3 replies · 2 participants
  • e

    Eric Ampire [MOD]

    07/31/2020, 11:08 AM
    Hi to you, how can I call the emit method in the body of a lambda? Is that a good approach to the code on capture ?
    w
    o
    +1
    4 replies · 4 participants
  • a

    asad.awadia

    07/31/2020, 1:02 PM
    fun main() {
      val apiRequest = 1
      var apiResponse = ""
      runBlocking {
        apiResponse = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someApiCallThatReturns(apiRequest) }
      }
    }
    is ‘returning responses’/‘sending arguments’ responses from one thread/coroutines on different didspatchers to another like this safe to do?
    b
    4 replies · 2 participants
  • n

    Nikky

    07/31/2020, 3:59 PM
    i have to use a rather terrible java api thats basically 1. set callback 2. call function and the callback gives me the return value how can i wrap such a structure in a
    suspend fun
    ?
    s
    14 replies · 2 participants
  • z

    zak.taccardi

    07/31/2020, 4:54 PM
    withContext(EmptyCoroutineContext) { .. }
    basically does nothing right?
    s
    t
    2 replies · 3 participants
  • s

    Sam Garfinkel

    07/31/2020, 4:56 PM
    Can anyone explain why the
    doSomething()
    in this snippet prevents the outer
    run()
    loop from continuing? You’ll notice that
    "Continuing to run"
    is printed after
    "doSomething with $hello done"
    which is the opposite pattern I’m looking for.
    broken.kt
    z
    o
    9 replies · 3 participants
  • i

    iseki

    07/31/2020, 11:05 PM
    Why
    suspendCancellableCoroutine
    is experiment but
    suspendCoroutine
    is not?
    o
    3 replies · 2 participants
  • g

    Gopal S Akshintala

    08/02/2020, 1:09 PM
    If I have a
    List<A>
    and a fn
    suspend (A) -> B
    , how can I apply this fn on the list in parallel?
    t
    n
    +2
    4 replies · 5 participants
  • l

    Lukas Lechner

    08/03/2020, 7:34 AM
    Are there any valid use cases for passing your own
    Job()
    object to
    launch
    or
    async
    ? For most use cases, its better to launch them in another scope or use
    superVisorScope{}
    if you want to use
    SupervisorJob
    , right?
    g
    z
    3 replies · 3 participants
  • r

    rmyhal

    08/03/2020, 1:11 PM
    What is equivalent to RxJava PublishSubject in coroutine channels?
    o
    a
    +3
    12 replies · 6 participants
  • a

    andylamax

    08/03/2020, 1:17 PM
    Hello all, so I am seeing a new keyword (
    coroutines-native-mt
    ) being passed around. May someone please explain to me what it is and its difference to
    coroutines-native
    ?
    t
    1 reply · 2 participants
  • j

    jenji

    08/03/2020, 5:48 PM
    Didn’t think before posting in #general, but this seems more appropriate to ask here.
    t
    2 replies · 2 participants
  • k

    Koya Sivaji

    08/03/2020, 9:50 PM
    Hi, am new to coroutines and flows and facing an issue with usage of Flows. Below is the code
    DeviceDao{
    @Query("SELECT * FROM devices")
        abstract fun getAllDevices(): Flow<List<Device>>
    }
    Repository layer
    fun getAllDevices() = database.deviceDao().getAllDevices()
    This repository method called form view model as below and every thing works fine
    viewModelScope.launch {
                homes = homeRepository.homes.asLiveData()
                devices = deviceRepository.getAllDevices().asLiveData()
            }
    Issue I am facing: Added another method at repository layer like below
    private suspend fun deleteDevicesNotInLambdaResponse(deviceJsonList: List<Device>) {
    
        var localDevices = emptyList<Device>()
        database.deviceDao().getAllDevices().collect {
            localDevices = it
          }
    
    
    //. the below code never executes
    
            val localDeviceIds = localDevices.map { it.deviceId }
            val remoteDeviceIds = deviceJsonList.map { it.deviceId }
    
            val localDevicesNotInLambdaResponse = localDeviceIds.filterNot {     remoteDeviceIds.contains(it) }
            database.deviceDao().deleteDevices(localDevicesNotInLambdaResponse)
        
    }
    Basically, here I want to get all local devices and find out which are not in API response and delete those devices from local data base As commented above, the code below the comment
    the below code never executes
    got never executed. Looks like I am missing some thing about how the Flow operator works Please suggest me how to fix this issue
    o
    o
    4 replies · 3 participants
  • l

    Lukas Lechner

    08/04/2020, 9:14 AM
    Are there any good use cases for launching coroutines in activities / fragments in the
    lifecycleScope
    ? IMO most (all?) coroutines should be started in
    viewModelScope
    because then they continue to run on orientation changes.
    d
    e
    +3
    5 replies · 6 participants
  • e

    Erik

    08/04/2020, 9:56 AM
    1. Is it safe to set the
    value
    of a
    MutableStateFlow
    from multiple threads? I guess it is, but then it is unknown which of the setters set the last value (which is also the last one collected/got from
    value
    )? The
    StateFlow
    docs mention 'All methods of data flow are thread-safe and can be safely invoked from concurrent coroutines without external synchronization', but does this include the
    value
    setter and getter? Seems unlikely to me.
    g
    4 replies · 2 participants
  • e

    Erik

    08/04/2020, 10:04 AM
    2. How can I implement a thread-safe
    MutableStateFlow.value
    read-and-write operation? I mean: first read the current
    value
    (this is thread-unsafe, because I don't know if another thread will change the value just after I read it), then use it to set it again. I can probably use a
    Channel
    for this, but how do I do this? And there are probably alternatives?
    h
    z
    11 replies · 3 participants
  • g

    George Theocharis

    08/04/2020, 10:48 AM
    Hello 👋 Is it correct that state flow will only emit the latest value? Seems I cannot collect every different state and assert the order, except the latest. With live data though you can with observe forever. Is something i can do to test that order of states?
    g
    w
    +1
    13 replies · 4 participants
  • g

    George Theocharis

    08/04/2020, 3:47 PM
    So is there an actual difference (well except the fact of the obvious thats a different tool) to return a mutable state flow as a: • StateFlow • asLiveData() From experimenting today sounds like
    mutableStateFlow.asLiveData()
    is pretty much best of both worlds as you can have access to the operators privately while exposing a lifecycle aware state? Is there any huge pitfall I haven’t think of?
    👍 1
    w
    s
    +2
    7 replies · 5 participants
  • t

    trevjones

    08/04/2020, 8:27 PM
    I am finding myself doing roughly:
    combine(one, two, three) { 1, 2, 3 -> Triple(1,2,3) }.flatMapLatest { (1, 2, 3) -> ... }
    is there a cleaner way built in to deal with that?
    t
    l
    4 replies · 3 participants
  • l

    Lukas Lechner

    08/05/2020, 6:55 AM
    Is there any difference beween calling
    .cancel()
    on the job of the scope VS calling
    .cancel()
    on the scope itself? Lots of blogpost recommend to keep a reference to the
    job
    in order to be able to cancel it, although IMO this is not necessary, as cancelling the scope itself has the exact same effect. Am I correct?
    t
    e
    +3
    7 replies · 6 participants
  • s

    Sudhir Singh Khanger

    08/05/2020, 9:26 AM
    I fetch some data from the server and forward it to via a Flow object. I need to do some accessory work based on the fetched data but I don't need to transform the data which remains as it is. It doesn't look like I would use
    map
    operator here. Where should I do this accessory work? In the repository before the values are emitted or in the UI where the data is delivered. Or if there is another operator that let's me do such accessory work.
    w
    3 replies · 2 participants
  • s

    Sam Garfinkel

    08/05/2020, 2:44 PM
    Is it safe to read from an
    InputStream
    in a
    flow { }
    builder? Getting warnings from IntelliJ about inappropriate blocking calls.
    s
    g
    +1
    31 replies · 4 participants
  • d

    dan.the.man

    08/05/2020, 3:27 PM
    Does anyone know how to correctly test a channel?
    coroutinesTestRule.testDispatcher.runBlockingTest {
                var latestNav: NavEvent? = null
                navChannel.consumeEach {
                    latestNav = it }
                vm.handleAction(NearbyListingClicked(nearbyListing))
                assertEquals(latestNav, OpenListing(variant.listing!!.wmid.toString()))
            }
    But I'm just getting
    java.lang.IllegalStateException: This job has not completed yet
    The
    Channel.consumeEach
    appears to be blocking, which I don't think it should be
    s
    9 replies · 2 participants
  • m

    Marc Knaup

    08/05/2020, 4:37 PM
    Is the new coroutines debugger not available in Android Studio?
    z
    r
    7 replies · 3 participants
  • o

    okue

    08/07/2020, 4:59 AM
    Hi, all. Does anyone use BlockHound integration with coroutines and reactor? When the code
    Mono#awaitFirst()
    is executed, BlockHound detected blocking call here: https://github.com/Kotlin/kotlinx.coroutines/blob/1.3.8/reactive/kotlinx-coroutines-reactive/src/ReactiveFlow.kt#L145 Off course, this detection occurs only once or twice after starting my application. After
    contextInjector
    is initialized, this detection is not warned any more. Though this is not so a severe problem, I want to know a good way to suppress this error. It would be happy if kotlinx.coroutines BlockHound integration resolves this issue.
    e
    4 replies · 2 participants
Powered by Linen
Title
o

okue

08/07/2020, 4:59 AM
Hi, all. Does anyone use BlockHound integration with coroutines and reactor? When the code
Mono#awaitFirst()
is executed, BlockHound detected blocking call here: https://github.com/Kotlin/kotlinx.coroutines/blob/1.3.8/reactive/kotlinx-coroutines-reactive/src/ReactiveFlow.kt#L145 Off course, this detection occurs only once or twice after starting my application. After
contextInjector
is initialized, this detection is not warned any more. Though this is not so a severe problem, I want to know a good way to suppress this error. It would be happy if kotlinx.coroutines BlockHound integration resolves this issue.
Ah, it’s enough to ignore “kotlinx.coroutines.reactive.ReactiveFlowKt#clinit“.
Untitled
e

Erik

08/07/2020, 10:38 AM
This could be a nice self-question-and-answer on 😒tackoverflow:, so that others that run into this issue can publicly find a solution.
😀 1
o

okue

08/11/2020, 8:58 AM
I’ve opened the issue
https://github.com/Kotlin/kotlinx.coroutines/issues/2190
View count: 12