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

    Marc Knaup

    10/13/2020, 1:32 AM
    Property delegation to a
    (Mutable)StateFlow
    may be useful 🙂
    val state by someStateFlow()
    …
    println(state)
    
    var foo by someMutableStateFlow()
    …
    state = newFoo()
    ➕ 7
    e
    • 2
    • 1
  • o

    Orhan Tozan

    10/13/2020, 1:22 PM
    Is
    StateFlow<T>
    mapping a planned feature? Right now I stick with Flow instead of StateFlow<T> because it stops me from doing something like this:
    // Example 1
    val name: StateFlow<String> = ...
    val greeting: StateFlow<String> = name.map { name ->
        "Hi, $name!"
    }
    
    // Example 2
    val a: StateFlow<Int> = ...
    val b: StateFlow<Int> = ...
    
    val sum: StateFlow<Int> = combine(a, b) {a, b -> a + b }
    j
    z
    • 3
    • 9
  • v

    Vsevolod Tolstopyatov [JB]

    10/13/2020, 1:42 PM
    📣 📣 📣 kotlinx.coroutines 1.4.0-M1 is here! •
    SharedFlow
    for managing hot sources of data •
    shareIn
    and
    stateIn
    operators to transform a cold
    Flow
    into a hot one • Channel cancellation atomicity is reworked, and API for closeable resource transfer is introduced And more, full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.4.0-M1
    🔥 21
    🎉 22
    g
    e
    +2
    • 5
    • 6
  • z

    zak.taccardi

    10/13/2020, 4:21 PM
    is there an issue for tracking “sliceable dispatchers”?
    ➕ 3
    b
    e
    • 3
    • 3
  • m

    Marc Knaup

    10/13/2020, 6:34 PM
    Is there a way to access coroutine information during debugging without using breakpoints?
    No coroutine information found
    Target VM is not paused by breakpoint request. Evaluation of methods is not possible in this mode
    e
    • 2
    • 3
  • d

    dalewking

    10/13/2020, 10:21 PM
    Just realized that SharedFlow was only released today, so maybe I need to be a little more patient
    a
    • 2
    • 2
  • m

    Marc Knaup

    10/14/2020, 1:03 PM
    val coroutineContext = parentScope.coroutineContext + CoroutineName("foo")
    Is there a difference between
    GlobalScope.launch(coroutineContext) {…}
    and
    CoroutineScope(coroutineContext).launch {…}
    ?
    👀 1
    l
    • 2
    • 2
  • m

    Marc Knaup

    10/14/2020, 1:14 PM
    MutableStateFlow
    is great for passing around a shared cache, or is it? 🤔
    l
    c
    • 3
    • 12
  • c

    CLOVIS

    10/14/2020, 5:40 PM
    Hi! I currently have this pipeline:
    val input: Flow<MyObject> = ...
    val output = input.map { it.toOtherObject() }
    I would like the calls to
    toOtherObject
    to be ran in parallel, and I would like an exception in one call not to stop the others. I tried:
    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    val output = input.map {
      scope.async {
        it.toOtherObject()
      }
    }.map { it.await() }
    But this is still sequential, and not parallel. What am I doing wrong?
    l
    t
    • 3
    • 5
  • o

    Oleg Siboglov

    10/14/2020, 7:09 PM
    Hey everybody. I have a quick question. In this example, why does
    joining
    occur before
    second started
    ? I’m running this in IntelliJ if that makes any difference.
    fun main() = runBlocking {
        val job = GlobalScope.launch {
            val deferredOne = async(<http://Dispatchers.IO|Dispatchers.IO>) {
                println("first started")
                delay(1_000)
                println("first finished")
            }
            val deferredTwo = async(<http://Dispatchers.IO|Dispatchers.IO>) {
                println("second started")
                delay(2_500)
                println("second finished")
            }
            println("joining")
            deferredOne.join()
            deferredTwo.join()
            println("complete")
        }
        job.join()
    }
    This is the output.
    first started
    joining
    second started
    first finished
    second finished
    complete
    z
    c
    • 3
    • 3
  • m

    Marc Knaup

    10/15/2020, 12:47 AM
    Is there a way to check if coroutines are available?
    if (coroutinesAvailable) GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { … } else …
    s
    z
    g
    • 4
    • 9
  • a

    Animesh Sahu

    10/15/2020, 3:54 AM
    Why
    Flow<T>.collectWhile(predicate)
    is internal in kotlinx.coroutines.flow ? It could be useful to suspend a coroutine till value matches some predicate. Is
    Flow<T>.first(predicate): T
    considered to be used (as it utilizes the collectWhile) or something else to be used?
    l
    e
    e
    • 4
    • 4
  • m

    Marc Knaup

    10/15/2020, 8:07 PM
    Is all that parking overhead from coroutines? Are there approaches to get that down? Looks like that 50% of the application’s CPU time is spent on locking.
    👀 2
    s
    d
    +4
    • 7
    • 50
  • r

    Ricardo C.

    10/16/2020, 2:59 PM
    Hello! I’m currently having an issue where wrapping a callback + switching the context will throw even when wrapping everything inside a Result. The weird part is that I’m not throwing anything, just creating a Result.failure with the exception. Removing withContext will fix the crash, but then I’m not sure how to run on another thread (Code inside the thread)
    m
    l
    • 3
    • 10
  • w

    why

    10/16/2020, 9:41 PM
    Hi, I need something like AtomicReference in KMP project, any ideas?
    s
    a
    • 3
    • 4
  • u

    ursus

    10/17/2020, 5:07 AM
    Is low level synchronized block still cool in coroutines? The usual copy load+save use case... Or maybe updating StateFlow instance via reducing of the current value + change
    m
    l
    +2
    • 5
    • 34
  • u

    ursus

    10/17/2020, 5:12 AM
    Is having a single threaded dispatcher or semaphore more idiomatic?
    l
    t
    • 3
    • 2
  • c

    CLOVIS

    10/17/2020, 12:21 PM
    What is the correct way of catching an exception in
    Flow.flatMapMerge
    ? I have this:
    val f: Flow<CustomObject> = ...
    f.flatMapMerge {
      it.customFlow()
    }
    This works fine as long as there is no exception, however if there is one, the entire flow is cancelled. I tried to write
    f.flatMapMerge {
      try {
        it.customFlow()
      } catch(e: Throwable) {
        println("Caught")
        emptyFlow()
    }
    } but that still cancels the flow, instead of just skipping items for which the conversion fails.
    z
    • 2
    • 3
  • z

    ziv kesten

    10/17/2020, 1:54 PM
    Is there a way to pass events from websocket to view model without RxJava and callback? RxJava is just to big to implement in my project just for this need. Flow is still not ready for production (is it?) And liveData does not seem like a good fit (no need for lifecycle awareness in this case)
    z
    • 2
    • 4
  • i

    iex

    10/17/2020, 4:16 PM
    How do I write
    Observable.just
    with channels?
    w
    • 2
    • 4
  • u

    ursus

    10/18/2020, 2:17 AM
    Hi, im migrating from rx java. Is there a way to make this flow synchrounous on main thread in android?
    class MainActivity : AppCompatActivity() {
    
        private val scope = MainScope()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
    		Log.d("Default", "a")
            scope.launch {
                Log.d("Default", "b")
                flowOf(1)
                    .collect { Log.d("Default", "coll=$it t=${Thread.currentThread().name}") }
            }
            Log.d("Default", "c")
        }
    }
    
    prints:
    2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: a
    2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: c
    2020-10-18 04:14:26.848 21786-21786/sk.foo.flowplayground D/Default: b
    2020-10-18 04:14:26.851 21786-21786/sk.foo.flowplayground D/Default: coll=1 t=main
    
    I want:
    2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: a
    2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: b
    2020-10-18 04:14:26.848 21786-21786/sk.foo.flowplayground D/Default: coll=1 t=main
    2020-10-18 04:14:26.851 21786-21786/sk.foo.flowplayground D/Default: c
    i
    z
    • 3
    • 11
  • d

    dorf

    10/18/2020, 7:57 AM
    is it common practice to pass around a coroutine context? I come from the C# world, and I’m trying to figure out how to actually call suspend functions
    e
    g
    u
    • 4
    • 7
  • c

    caelum19

    10/18/2020, 2:46 PM
    Has anyone had success evaluating an expression with the debugger recently? Getting
    Class 'androidx.compose.ui.layout.LayoutCoordinates' is compiled by a new Kotlin compiler backend and cannot be loaded by the old compiler
    etc
    r
    z
    • 3
    • 4
  • u

    ursus

    10/18/2020, 4:37 PM
    Hi, im trying to learn coroutines/Flow I want to subscribe my
    viewModel.state
    flow in android Activity, between onStart and onStop I do that, and notice that after having activity.onStop called, next activity.onStart doesn't start listening to the flow So I conclude scopes are not reusable But this is android reality and I need that. I need equivalent of rx
    compositeDisposable.clear()
    Is the only solution to have abstraction over the scope which will create new scope instances?
    f
    i
    • 3
    • 5
  • j

    Joaquim Ley

    10/18/2020, 6:15 PM
    Hello everyone, has anyone had any issues related to coroutines/ktor/multiplatform? So when using the
    1.3.9-native-mt-2
    it works on iOS but not for Android • const val kotlinCoroutines = “1.3.9-native-mt-2” With
    1.4.0-M1
    works for android but not iOS • const val kotlinCoroutines = “1.4.0-M1"
    c
    j
    • 3
    • 14
  • n

    nitrog42

    10/19/2020, 9:36 AM
    is there any way to find the origin of a JobCancellationException on Android ? There is no stacktrace displayed in logcat 😢 the debug probes still doesn't look available
    g
    • 2
    • 10
  • l

    Luis Munoz

    10/19/2020, 8:01 PM
    which is better the first block or the second?
    scope.launch {
                while (isActive) {
                    launch {
                        val record = aKafkaConsumer.poll(Duration.ofMillis(200))
                        log.debug().log("[received records] - count={}", record.count())
                        record.forEach {
                            callback(KafkaMessage(it.key(), it.value()))
                        }
                    }
                }
            }
            
     
            scope.launch {
                while (isActive) {
                    val record = aKafkaConsumer.poll(Duration.ofMillis(200))
                    log.debug().log("[received records] - count={}", record.count())
                    record.map {
                        launch {  callback(KafkaMessage(it.key(), it.value()))    }
                    }.joinAll()
                }
            }
    z
    • 2
    • 5
  • r

    Rechee Jozil

    10/19/2020, 9:52 PM
    Unique CoroutineName per child coroutine Right now if you pass a CoroutineName in a context, that name is propagated down to children Coroutines. I guess this makes sense. That's behavior for any context element except for Job. I think it would be nice to give children Coroutines unique names based off their parents CoroutineName. Does that make sense? In the end... I would like a way to identify children Coroutines vs top level Coroutines. Is there a way to do this?
    m
    • 2
    • 5
  • n

    ntherning

    10/20/2020, 6:48 AM
    Hi! I'm running into an issue with
    Mutex.withLock
    and unexpected freezing in my iOS app when upgrading my project to kotlin 1.4.10 and coroutines 1.3.9-native-mt-2. I think I have been able to make a simple reproduction case:
    runBlocking(newSingleThreadContext("thread")) {
        val mutex = Mutex().apply { ensureNeverFrozen() }
        launch {
            runCatching { mutex.withLock { delay(1000) } }.exceptionOrNull()?.printStackTrace()
        }
        launch {
            runCatching { mutex.withLock { delay(1000) } }.exceptionOrNull()?.printStackTrace()
        }
    }
    This launches two coroutines in the same worker. Both tries to take the lock and then delays for 1 sec while holding it. As everything happens within the same worker thread I would not expect any mutability issues. But... This is what happens:
    kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlinx.coroutines.sync.MutexImpl.LockedQueue@788375b8
        at kfun:kotlin.Throwable#<init>(kotlin.String?){} + 93 (kotlin/kotlin/Throwable.kt:23:37)
        at kfun:kotlin.Exception#<init>(kotlin.String?){} + 91 (kotlin/kotlin/Exceptions.kt:23:44)
        at kfun:kotlin.RuntimeException#<init>(kotlin.String?){} + 91 (kotlin/kotlin/Exceptions.kt:34:44)
        at kfun:kotlin.native.concurrent.InvalidMutabilityException#<init>(kotlin.String){} + 91 (kotlin/kotlin/native/concurrent/Freezing.kt:22:60)
        at ThrowInvalidMutabilityException + 690 (kotlin/kotlin/native/concurrent/Internal.kt:92:11)
        at MutationCheck + 108
        at kfun:kotlinx.coroutines.sync.MutexImpl.LockedQueue.<set-owner>#internal + 102 (sync/Mutex.kt:350:19)
        at kfun:kotlinx.coroutines.sync.MutexImpl#unlock(kotlin.Any?){} + 3740 (sync/Mutex.kt:327:29)
        at kfun:MutexInvalidMutabilityTest.$doTest$lambda-2$lambda-0COROUTINE$0.invokeSuspend#internal + 2206 (MutexInvalidMutabilityTest.kt:16:61)
        ...
    You can find the full code and full stack trace it in this gist: https://gist.github.com/ntherning/a1bf85d44a5989d66677762c15587552 Is this expected behavior? Perhaps I am doing something stupid? Or a bug in
    MutexImpl
    ?
    t
    m
    • 3
    • 6
  • j

    joney

    10/20/2020, 7:47 AM
    Anyone knows if/when
    SharedFlow
    is planned to be included in
    native-mt
    ?
    g
    l
    d
    • 4
    • 5
Powered by Linen
Title
j

joney

10/20/2020, 7:47 AM
Anyone knows if/when
SharedFlow
is planned to be included in
native-mt
?
g

gildor

10/20/2020, 7:59 AM
it probably will be included, native-mt is developed on top of master, so probably when coroutines 1.4 will be released, and native-mt version of 1.4 will be ready, it will include all changes from 1.4
🙏 1
👍 1
Though, it doesn’t meant that native-mt will be ready soon after 1.4 release
🆗 1
l

louiscad

10/20/2020, 8:45 AM
https://github.com/Kotlin/kotlinx.coroutines/tree/native-mt-1.4.20
👀 2
👍 2
d

dalewking

10/26/2020, 1:00 PM
What is the point of the reference to the native-mt-1.4.20 branch since it does not have SharedFlow? I like others are patiently waiting for the ability to use SharedFlow in native (iOS in my case)
l

louiscad

10/26/2020, 1:01 PM
I think it's WIP and it's going to be merged before 1.4.20.
🙏 1
View count: 5