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

    nitrog42

    10/20/2020, 10:07 AM
    can anybody using coroutine 1.4.0-M1 confirm that a
    MutableSharedFlow(replay = 0)
    doesn't emit values ? 😕 the same code works if replay = 1 (but I don't want to replay first value each time 😢 )
    m
    • 2
    • 26
  • p

    Pablo

    10/20/2020, 10:13 AM
    Hello on my presenter I'm getting a
    CoroutineScope
    and a
    CoroutineDispatcher
    is it mandatory to implement in the
    onDestroy()
    the cancel of them? what happens if I don't do this?
    a
    i
    • 3
    • 8
  • f

    fjoglar

    10/20/2020, 11:31 AM
    Hi all! I'm trying to call 2 consecutive `Flow`s from an android
    Activity
    , I'm getting:
    java.lang.IllegalStateException: ReceiveChannel.consumeAsFlow can be collected just once
    The code I'm executing from is this:
    private fun getCustomer() = lifecycleScope.launch {
            isLoading = true
    
            // Get the user's customer code.
            GetUserDetailsUseCase().getCustomer().collect { result ->
                when (result) {
                    is Result.Success -> uploadDocument(result.data)
                    is Result.Error -> showPopup(result.errorMessageResId)
                }
            }
        }
    
        private fun uploadDocument(customer: Customer) = lifecycleScope.launch {
            this@SignUpDocumentValidationActivity.customer = customer
            // Upload document and get URL.
            val filename = "${System.currentTimeMillis()}${customer.code}"
            when (val uploadResult = UploadImageUseCase().uploadImage(
                scaleImage(),
                filename
            )) {
                is Result.Success -> {
                    Logger.i(TAG, "Image $filename.jpg uploaded successfully.")
                    sendDocumentAndContinue(uploadResult.data)
                }
                is Result.Error -> showPopup(uploadResult.errorMessageResId)
            }
        }
    
        private fun sendDocumentAndContinue(documentUrl: String) = lifecycleScope.launch {
            // Send document to backend
            UpdateDocumentUseCase().updateDocument(
                customer!!,
                DocumentType.values()[currentStep],
                documentUrl
            ).collect { result ->
                when (result) {
                    is Result.Success -> {
                        deleteImage()
                        isLoading = false
                        nextStep()
                    }
                    is Result.Error -> showPopup(result.errorMessageResId)
                }
            }
        }
    How can I get rid of this issue and call the two collect() methods secuentially? Thanks!
    t
    • 2
    • 1
  • p

    Patrick

    10/20/2020, 12:43 PM
    Is it possible to use coroutine code from Java?
    j
    d
    +3
    • 6
    • 11
  • s

    Shawn Witte

    10/20/2020, 9:10 PM
    I have a
    suspend
    function that launches several operations (syncing individual pieces of local data) and I don't want this function to be run more than once simultaneously (if we try to POST the same data twice, then we get two new entries on the server side). What is the preferred practice for preventing a second simultaneous execution of this function? I have an idea, but I wanted the community opinion since there was some concern about my answer in a code review.
    l
    • 2
    • 4
  • d

    dan.the.man

    10/20/2020, 9:34 PM
    Is a
    BroadcastChannel(BUFFERED)
    still the best replacement for PublishSubject?
    b
    t
    • 3
    • 2
  • w

    william

    10/20/2020, 11:53 PM
    looking for a flow operator that does something like input: Foo output: List<Foo> everytime the upstream flow emits, the operator would emit a list of this value and any previous values that are emitted
    m
    e
    • 3
    • 10
  • s

    Sachin Maharana

    10/21/2020, 7:23 AM
    I have seen examples of using GlobalScope.launch and runBlocking to create coroutines. How i can create coroutines without using the above two options? Using runBlocking as coroutine builder launches coroutines on a single thread, but i don't want to that. And GlobalScope launches in the root scope and has to be taken care of. What other options i have?
    b
    b
    +2
    • 5
    • 5
  • k

    KV

    10/21/2020, 12:43 PM
    Hello guys, I have a function
    buildRequestUrl
    which build the URL including headers and query parameters. Now I am working on tests for api call's response. and I am debugging the code where I build the URL which is this
    val uriBuilder = Uri.parse(baseUrl).buildUpon()
    But the issue is it throws null pointer exception and result is null (see attached screenshot) How do I solve this issue? I am using below library
    testImplementation 'junit:junit:4.13'
        testImplementation "org.mockito:mockito-core:3.4.6"
        testImplementation 'androidx.arch.core:core-testing:2.1.0'
        testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.9'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    I am using below class
    @ExperimentalCoroutinesApi
    class TestCoroutineRule : TestRule {
    
        private val testCoroutineDispatcher = TestCoroutineDispatcher()
    
        private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)
    
        override fun apply(base: Statement, description: Description?) = object : Statement() {
            @Throws(Throwable::class)
            override fun evaluate() {
                Dispatchers.setMain(testCoroutineDispatcher)
    
                base.evaluate()
    
                Dispatchers.resetMain()
                testCoroutineScope.cleanupTestCoroutines()
            }
        }
    
        fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) =
            testCoroutineScope.runBlockingTest { block() }
    }
    I am using the below rule in the test class:
    @get:Rule
        val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
    
        @get:Rule
        val testCoroutineRule = TestCoroutineRule()
    m
    • 2
    • 18
  • b

    Big Chungus

    10/21/2020, 12:48 PM
    I'm getting random
    kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 15000 ms
    (Not serring timeouts anywhere explicitly). Does anyone know how I could increase this?
    m
    • 2
    • 12
  • m

    Mark

    10/21/2020, 1:08 PM
    I want to use
    Flow.combine(Flow)
    However, the second flow is not known until at some point in the progression of the original Flow (at which point, the second flow can be derived). At the moment, I achieve this by (and it feels like a very nasty hack) having a
    MutableStateFlow
    and updating that flow from a coroutine launched from within
    onEach
    (just before
    combine
    ). So then we use
    combine(MutableStateFlow)
    . But how to do this properly?
    l
    m
    +2
    • 5
    • 36
  • w

    william

    10/21/2020, 11:27 PM
    I have a
    Channel(Channel.UNLIMITED)
    in use to act as a queue between coroutines but am having trouble with my receiving coroutine not seeing any of what the producer is giving. could there be an issue from performing both of this in the scope of
    <http://Dispatchers.IO|Dispatchers.IO>
    (which i believe is multithreaded in java) ? should i be using a single threaded coroutine scope / dispatcher for this to work?
    z
    • 2
    • 8
  • s

    Sachin Maharana

    10/22/2020, 12:10 PM
    I am not sure what i am doing wrong here. Can anybody point out the obvious. 😅
    import kotlinx.coroutines.GlobalScope
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.*
    import kotlin.system.measureTimeMillis
    import kotlinx.coroutines.delay
    
    fun main() = runBlocking {
        println("${Thread.activeCount()} threads active at the start")
        val time = measureTimeMillis {
            createCoroutines(10_000)
        }
        println("${Thread.activeCount()} threads active at the end")
        println("Took $time ms")
    }
    
    suspend fun createCoroutines(amount: Int) {
        val jobs = ArrayList<Job>()
        for (i in 1..amount) {
            jobs += launch {
                delay(1000)
            }
        }
        jobs.forEach {
            it.join()
        }
    }
    w
    b
    • 3
    • 6
  • f

    Filip de Waard

    10/22/2020, 12:26 PM
    We’re getting a flow of rows from the database (through r2dbc) like this:
    db.execute { ... }.asType<Foo>().fetch().flow()
    Now we want to return a Map. Two ways of doing that are:
    db.execute { ... }.asType<Foo>().fetch().flow().fold(mapOf()) { acc, it -> acc + (transform(it.bar) to it.baz) }
    or:
    db.execute { ... }.asType<Foo>().fetch().flow().map(transform(it.bar) to it.baz).toList().toMap()
    Which is better and why?
    j
    e
    • 3
    • 8
  • r

    Rechee Jozil

    10/22/2020, 4:10 PM
    How do you get root coroutine context? Or can you walk through parent contexts?
    z
    • 2
    • 4
  • a

    Adam Miskiewicz

    10/22/2020, 4:56 PM
    At Airbnb, we use Kotlin and coroutines in some of our server-side code. The workload for each request is fully async — there’s no blocking code that runs during the life of the request. For the most part, things work just fine, as you’d expect. However, as we load test these services and bring them to a breaking point, we see latency sky rocket, queuing start to occur at the web server layer (we use Dropwizard and non-blocking jetty APIs, so under normal operation, there is absolutely no queuing), and eventually heap exhaustion as all of this work is queued and requests never complete. Now of course, some of this behavior is expected — every service has its breaking point 🙂. In our Java services, however, which has a more mature service framework, we use standard patterns such as CoDel (controlled delay, https://en.wikipedia.org/wiki/CoDel), adaptive queuing, etc, to perform some load shedding to ensure that, even under heavy load, while the service may degrade, it never gets into an unrecoverable state. This has worked well for us, and I’d like to do similar things in our Kotlin services that use Coroutines. Does anyone have any insight into how to apply a load shedding algorithm (bulkheading, controlled delay, etc) for coroutines, while still leveraging the default work-stealing dispatcher?
    CoroutineScheduler
    doesn’t expose any public APIs to get it’s current “state”, meaning that there’s no way to really get much insight into the state of the default dispatcher. TL;DR — I want to figure out how to structure my application such that, when we’re saturating the CPU (and thus all the default dispatcher threads are super busy doing “stuff”), I can start to throw some back pressure and reject some requests, rather than continuing to accept hundreds/thousands of requests and causing the server to completely become unresponsive. And notably, I want to be able to cause this behavior with a mechanism that doesn’t require a ton of tuning per-service — I don’t want to do this strictly with a “request rate limit” or something like that. I’d like it to be much more adaptive, ideally.
    l
    e
    +2
    • 5
    • 36
  • f

    Florian

    10/22/2020, 5:18 PM
    Where would you put a register/signUp method that needs to execute some extra asynchronous work after the signUp process itself is finished? When I put it into a SignUpViewModel that is scoped to SignUpFragment the viewmodelScope is canceled too early (because as soon as we signed up, we leave this fragment).
    b
    s
    • 3
    • 8
  • l

    Luis Munoz

    10/22/2020, 6:55 PM
    Anyone have an example of a producer and multiple worker consumer pattern using flow, shareIn?
    l
    t
    • 3
    • 3
  • w

    william

    10/22/2020, 10:21 PM
    anyone know why the coroutine debugger wouldn't be showing up in intellij / android studio? i'm using kotlin 1.4.10 and coroutines 1.3.9
    u
    • 2
    • 3
  • m

    MJegorovas

    10/23/2020, 8:49 AM
    Is
    offset
    variable in this method safe to use in multiple threads?
    suspend fun InputStream.readByChunks(
        fileSize: Long,
        chunkSize: Int,
        block: suspend (bytes: ByteArray, offset: Long) -> Unit
    ) {
        var offset = 0L
    
        this.buffered().use { input ->
            while (offset != fileSize) {
                val buffer = if (offset + chunkSize < fileSize) {
                    ByteArray(chunkSize)
                } else {
                    ByteArray((fileSize - offset).toInt())
                }
    
                val read = input.read(buffer)
                block(buffer, offset)
                offset += read
            }
        }
    }
    b
    e
    • 3
    • 6
  • w

    william

    10/23/2020, 12:11 PM
    has anyone else had trouble with using a channel in a multiplatform context? right now i'm testing on android but for some reason my iterator over my channel is not receiving any values. when i attempt to reduce the problem and run it in a jvm only project it works fine though
    class PersistentWsClient() {
    	private val scope = CoroutineScope(Dispatchers.Default)
        private val sendingQueue = Channel<Frame>(UNLIMITED)
    
        fun open(host: String, path: String, port: Int = 8080) {
            scope.launch {
                this@PersistentWsClient.e("waiting for messages")
                for (msg in sendingQueue) {
                    this@PersistentWsClient.e(msg.toString())
                }
            }
        }
    
        fun send(payload: Frame) {
            scope.launch {
                for (i in 0..10) {
                    delay(500)
                    sendingQueue.offer(payload)
                    this.e("offering $payload")
                }
            }
            sendingQueue.offer(payload)
        }
    }
    (i have stripped away some extra code). In this example i only ever get
    waiting for messages
    offering <payload>
    offering <payload>
    ...
    t
    • 2
    • 13
  • a

    Albert

    10/23/2020, 12:31 PM
    1. Why am I seeing: java.lang.NoClassDefFoundError: Could not initialize class kotlinx.coroutines.CancelledContinuation 2. On my local machine I don't get stack overflow, on our CI pipeline I get the
    StackOverflowError
    error
    m
    • 2
    • 4
  • u

    ursus

    10/24/2020, 3:40 AM
    or other words, this of the lambda is Transaction instance and all consumer methods should be a extension on Transcation is it possible to enforce this without a compiler plugin?
    g
    • 2
    • 11
  • u

    ursus

    10/24/2020, 1:54 PM
    2) coming from rxjava
    Observable.just(1).startWith(0)
    emits 0,1 flow
    flowOf(1).onStart { emit(0) }
    emits 1,0 is this by design? a rx fix? pretty foot gunny when mkgrating also, what if the actual flow is replayed? if its "below" the onStart, id assume it emits first which is not good
    g
    j
    f
    • 4
    • 11
  • j

    janvladimirmostert

    10/24/2020, 2:49 PM
    i have a suspend method that i want to make use of
    suspend fun lookupListings(): List<QueryListings.SelectListingsResult> {
    if i make use of runBlocking, i'm assuming it's physically blocking a thread until that suspend function completes, what is the better route to take here to get rid of the `runBlocking`s?
    class HomePage : PageResponse(
    	title = "Page Title",
    	description = "Page Description",
    ) {
    
    	val listings = runBlocking {
    		lookupListings()
    	}
    
        val somethingElse = runBlocking {
            suspendLookupSomethingElse()
        }
    Edit: this is on the JVM
    w
    • 2
    • 14
  • w

    william

    10/24/2020, 4:16 PM
    StateFlow
    appears to compare values before updating them (unlike
    LiveData
    ), so if I have a mutable list which I update and send to my
    MutableStateFlow
    it doesn't get published from the looks of it - unless I create a new list / copy it. Is that the right way to work around this?
    a
    • 2
    • 8
  • u

    ursus

    10/24/2020, 7:16 PM
    Android android studio folks? This happens to me all the time
    g
    • 2
    • 8
  • u

    ursus

    10/24/2020, 7:25 PM
    3) Its me with rxjava
    startWith
    and flow
    onStart
    again
    CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>).launch {
    	flowOf(1)
    		.onStart { emit(0) }
    		.collect {
    			stateFlow.value = it
    		}
    }
    
    -- is equivalent to:
    Observable.just(1)
    	.startWith(0) <---
    	.subscribeOn(<http://Schedulers.io|Schedulers.io>()) <---
    	.subscribe {
    		behaviorRelay.accept(it)
    	}
    
    -- In rx I use:
    Observable.just(1)
    	.subscribeOn(<http://Schedulers.io|Schedulers.io>()) <---
    	.startWith(0) <--- swapped
    	.subscribe {
    		behaviorRelay.accept(it)
    	}
    is this doable somehow in flow? (to not have the onStart emit coming from io thread)
    g
    • 2
    • 7
  • j

    Jeremy

    10/24/2020, 8:30 PM
    When declaring a suspend function within another suspend function. Is this a compiler bug?
    e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: wrong bytecode generated
    l
    • 2
    • 6
  • u

    ursus

    10/24/2020, 9:18 PM
    Coming from rx java I was waiting for the
    replay
    operators to migrate to Flow. I see the
    shareIn()
    but unsure what the scope parameter should be?
    g
    • 2
    • 2
Powered by Linen
Title
u

ursus

10/24/2020, 9:18 PM
Coming from rx java I was waiting for the
replay
operators to migrate to Flow. I see the
shareIn()
but unsure what the scope parameter should be?
g

gildor

10/25/2020, 3:31 AM
shareIn (and other operators which create hot flow) require scope on which this hot flow will work, because it starts collecting upstream flow and cache values, so to avoid violation of structured concurrence you need some scope to which this flow will be attached Let’s say if it inside of class with scope, use it, if it’s just top level thing which should be never cancelled, just use GlobalScope (but careful with it)
If GlobalScope is essentially the same what RxJava so no structured concurrence
View count: 4