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

    groostav

    06/17/2019, 9:52 AM
    My question is vastly less interesting: I've got a
    ReceiveChannel<String>
    that I'm looking to conflate on a duration of time, such that I can reduce the number of messages to a known rate. In Tomas Mikula's reactFX this is
    successionEnds(duration)
    . any idea what the easiest way to get this is?
    d
    • 2
    • 4
  • a

    Amanjeet Singh

    06/17/2019, 1:01 PM
    Is there something analogous to observable.create for Coroutines I found a way through channels just want to dug upon any different ways?
    g
    z
    • 3
    • 5
  • m

    Melih Aksoy

    06/17/2019, 1:55 PM
    Hey all, I’m trying to write a test that verifies some calls are made based on what is emitted by a
    flow
    , but having trouble test is finished before all emits happen. Following code works all fine if I add a
    delay
    after
    source.stateData.testObserve
    @Test
            @ExperimentalCoroutinesApi
            fun `should update state after load initial`() {
                val initialParams = mockk<PageKeyedDataSource.LoadInitialParams<Int>>(relaxed = true)
                val initalCallback = mockk<PageKeyedDataSource.LoadInitialCallback<Int, String>>(relaxed = true)
    
                runBlocking {
    
                    // Fake loading
                    source.loadInitial(initialParams, initalCallback)
    
                    source.stateData.testObserve {
                        it shouldBeInstanceOf Result.State::class
                    }
                }
            }
    I don’t think this is the right way , how do I test a
    flow
    correctly ? And since we’re on it, is there a way to verify a flow is collected / collected n times etc. ?
    • 1
    • 1
  • t

    tseisel

    06/17/2019, 2:07 PM
    What's the difference between
    flow<String> {
        emit("Foo")
    }
    and
    channelFlow<String> {
        send("Foo")
    }
    Apart from the receiver, that is
    FlowCollector
    in the first and
    ProducerScope
    in the second.
    j
    s
    • 3
    • 2
  • g

    gotoOla

    06/17/2019, 3:18 PM
    What are peoples goto solution for confining number of parallel coroutines? If I use a dispatcher with e.g. 20 threads I guess I can still executon infinite number of coroutines to execute on these threads?
    e
    • 2
    • 11
  • u

    ursus

    06/19/2019, 12:06 AM
    Is there a way I can "connect" another callsite to a running coroutine? sort of like hot observable, where observer can join in on the receiving of the value produced
    g
    • 2
    • 103
  • a

    Allan Wang

    06/19/2019, 1:09 AM
    Why does
    CoroutineScope.cancel(cause: CancellationException? = null)
    return
    Unit
    instead of
    Nothing
    ? Is there a difference if we don’t have a noncancellation scope? When should we use
    cancel
    vs
    throw CancellationException
    ? Question comes down to
    job.cancel
    vs
    throw
    e
    • 2
    • 1
  • u

    ursus

    06/19/2019, 1:48 AM
    https://github.com/JakeWharton/SdkSearch/blob/master/sync/src/commonMain/kotlin/com/jakewharton/sdksearch/sync/ItemSynchronizer.kt
    private val _state = ConflatedBroadcastChannel<SyncStatus>()
       val state: ReceiveChannel<SyncStatus> get() = _state.openSubscription()
    
      fun forceSync() {
        _state.offer(SyncStatus.SYNC)
        GlobalScope.launch {
          val result = if (load()) SyncStatus.IDLE else SyncStatus.FAILED
          _state.offer(result)
        }
      }
    how would you handle this if forceSync() took an parameter? Channel per params would be needed @gildor
    g
    • 2
    • 38
  • j

    Joan Colmenero

    06/19/2019, 12:53 PM
    Is there any configuration we have to do when using
    mockito
    and
    suspend fun
    ? I remember when I did unit testing with
    rxJava
    I had to create a
    Rule
    and things like that, do I have to do something special to make it work? Note: I'm using MVP not MVVM I don't know if it's a good point
    t
    • 2
    • 5
  • b

    blakelee

    06/19/2019, 6:20 PM
    Is there an easy way to test if a coroutine is leaking?
    u
    v
    • 3
    • 2
  • b

    basher

    06/19/2019, 6:32 PM
    Anyone know if there's going to be a coroutines 1.3.0-M* release soon that supports kotlin 1.3.40?
    t
    • 2
    • 2
  • p

    Patrick Jackson

    06/19/2019, 7:21 PM
    A strange experience with coroutines. I launched a coroutine, but it is only executed once I place a breakpoint and connect the degugger. I called
    delay()
    and then execute some code. Anyone experienced this before? I can post some code later if needed...
    g
    • 2
    • 1
  • a

    Andrew Gazelka

    06/19/2019, 7:59 PM
    any way to write this in a more idiomatic way? (particularly the exception throwing to exit
    collect {}
    )
    s
    b
    g
    • 4
    • 14
  • a

    Andrew Gazelka

    06/19/2019, 9:30 PM
    is there a more idiomatic way to do
    val hotFlow = baseFlow.conflate().broadcastIn(this).asFlow()
    ?
    @FlowPreview
    @ExperimentalCoroutinesApi
    fun main() = runBlocking<Unit> {
        val baseFlow = (1..10).asFlow().delayEach(1_000)
        val hotFlow = baseFlow.conflate().broadcastIn(this).asFlow()
        launch {
            hotFlow.collect {
                println("A: $it")
            }
        }
    
        delay(5_000)
        launch {
            hotFlow.collect {
                println("B: $it")
            }
        }
    }
    l
    • 2
    • 1
  • v

    Vlad

    06/20/2019, 11:11 AM
    TokenManager.kt
    z
    • 2
    • 4
  • u

    uhe

    06/20/2019, 11:34 AM
    What am I missing here? This should compile, right?
    GlobalScope.launch {
                flowOf(1,2,3,4,5)
                    .delayEach(500)
                    .map { it * it }
                    .collect { println(it) } // Type mismatch: inferred type is () -> ??? but FlowCollector<Int> was expected
            }
    t
    s
    +2
    • 5
    • 10
  • a

    Alexjok

    06/20/2019, 12:52 PM
    I have a case where I need subscribe to the channel and do some work with the data from this channel when it come. Data is coming from another coroutine at different time intervals. I have a code, how i can do it better?
    val channel = Channel<Int>(1)
    
    fun main() = runBlocking<Unit> {
        launcher().start()
        test().start()
    }
    
    fun CoroutineScope.launcher() = launch(start = CoroutineStart.LAZY) {
        while(isActive) {
            channel.send(i)
    		delay(Random.nextLong(100, 6000))
        }
        
    }
    
    fun CoroutineScope.test() = launch(start = CoroutineStart.LAZY) {
        while (true) {
            doSomething(channel.receive())
        }
    }
    
    fun doSomething(value: Int) {
        println(value)
    }
    d
    • 2
    • 3
  • e

    eygraber

    06/20/2019, 3:14 PM
    Is there an article that explains Flow in terms of RxJava? I find myself mentally comparing the two while reading Flow documentation, and I'm getting stuck on figuring out what corresponds to what. I'm thinking that since I already know most of the abstract concepts it would be helpful if it were spelled out in terms of the concrete concepts from rx, e.g. X in Flow correlates to Y in rx. Even a simple table would be helpful.
    g
    m
    s
    • 4
    • 13
  • p

    Paul N

    06/21/2019, 2:51 PM
    I've got a rest service that launches a couroutine via GlobalScope.launch. The coroutine is in turn calling 2 3rd party services (by lauching child corotuintes) which may take 15 minutes to complete, so I want my rest service to return straight away. When my coroutine eventually finishes I send a coroutine message back to the originator and everyone is happy. I have multiple tests for the above. I'm using mockk and junit 5 to mock the 3d part services, and clearing mocks before each tests. Because of this I'm experiencing errors in the coroutines kicked off by one test, because the next test is coming along and clearing the mocks that are waiting to be consumed by the coroutine. I can't not clear the mocks, because I want to guarantee behaviour of each test. Is there any way I can wait for a GlobalScope launched coroutine to finish before I launch the next test ?
    g
    • 2
    • 2
  • t

    tulio

    06/21/2019, 4:57 PM
    Does this equivalence table make sense?
    -.kt
    s
    v
    • 3
    • 9
  • s

    streetsofboston

    06/21/2019, 5:36 PM
    I have a question about
    Flow
    with and without a buffer, in this example:
    val flow = flow {
        for (i in 1..100) {
            emit(1)
            delay(200)
        }
    }.flowOn(Dispatchers.Main) // try replacing it with Dispatchers.IO... 
    
    MainScope().launch {
        flow.collect { 
            println(it)
            delay(1000)
        }
    }
    This prints out an item each 1200 milliseconds or so. This makes sense. When using
    buffer()
    , I can speed up the collecting a bit and print out an item each 1000 milliseconds or so. This also make sense to me. However, just replacing
    .flowOn(Dispatchers.Main)
    with
    .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
    , the print-outs now happen each 1000 milliseconds as well…. I expected the frequency to still be 1200 milliseconds. Is this to be expected, that even without a buffer (with a size > 0), the
    flow
    now acts as if it has a buffer with using different dispatchers like this?
    z
    e
    • 3
    • 24
  • s

    streetsofboston

    06/22/2019, 5:08 PM
    https://www.infoq.com/presentations/continuations-java/ Most of the talk is about Fibers, Continuations, Structure Concurrency, Sequences, etc.
    r
    n
    +2
    • 5
    • 6
  • r

    Robert Jaros

    06/22/2019, 10:01 PM
    I came across this article: https://dev.to/martinhaeusler/why-i-stopped-using-coroutines-in-kotlin-kg0 . Does anyone have any thoughts about these arguments? I personally use coroutines mostly on single-threaded JS platform but I'm very interested how they perform on the server-side.
    🤬 2
    s
    g
    +5
    • 8
    • 11
  • l

    Loránd

    06/23/2019, 11:39 AM
    I have a suspend fun that for some reason returns Kotlin.Unit when it is done and not the type i expected it to return, anyone had this problem before?
    d
    j
    • 3
    • 14
  • s

    serebit

    06/24/2019, 4:31 AM
    Why are suspend getters and
    suspend operator fun get
    not allowed? I assume there's reasoning for them
    m
    v
    +2
    • 5
    • 7
  • a

    Allan Wang

    06/24/2019, 9:24 AM
    Channel purpose is still edited, on case someone wants to change it back
    j
    s
    s
    • 4
    • 3
  • t

    tylerwilson

    06/24/2019, 6:28 PM
    Anybody have a link to a sample of muultiplatform common code to test methods that contain coroutines. I have seen dos about it, but I cannot get around the error of Dispatch.setMain message.
    e
    r
    • 3
    • 7
  • a

    Alexjok

    06/25/2019, 12:35 PM
    I have a stream and I want subscribe to it several listeners. How can I do it in Kotlin?
    m
    • 2
    • 9
  • b

    Bob Glamm

    06/25/2019, 2:36 PM
    fun foo(): (suspend () -> Int) = { 5 }
    👍 6
    j
    g
    +2
    • 5
    • 19
  • r

    rook

    06/25/2019, 4:06 PM
    Is there an IDE feature to see a trace of which methods are getting invoked from which threads? I have a crash happening in production occasionally where google maps functions are getting invoked off the main thread and I’m having a heck of a time trying to trace the call stack back to the originating
    launch
    l
    • 2
    • 4
Powered by Linen
Title
r

rook

06/25/2019, 4:06 PM
Is there an IDE feature to see a trace of which methods are getting invoked from which threads? I have a crash happening in production occasionally where google maps functions are getting invoked off the main thread and I’m having a heck of a time trying to trace the call stack back to the originating
launch
l

louiscad

06/25/2019, 4:35 PM
Do you ever use
GlobalScope
, or a scope that doesn't have an explicitly defined dispatcher? Or a dispatcher that is not
Dispatchers.Main
? Looking for that should help.
r

rook

06/25/2019, 4:44 PM
I do use
GlobalScope
for a couple of things at my repository layer
I was just hoping that maybe a static analysis tool existed that could figure out which scopes a given function was being invoked from
l

louiscad

06/25/2019, 4:48 PM
It uses
Dispatchers.Default
by default (hence the name). Cmd+shift+F (Search in Path) and cmd + click (go to declaration or find usages) are my favorite "static analysis tools". I'm not aware of something coroutines specific. You can still put CoroutineName into the scope's context, and log it just before the crashing code.
✅ 2
View count: 3