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

    jeggy

    06/11/2020, 9:29 AM
    I started using
    runBlockingTest
    and am now getting:
    java.lang.IllegalStateException: This job has not completed yet
    Is there some nice way to figure out which job has not been completed? Or do I need to find that out myself?
    a
    z
    • 3
    • 6
  • v

    vaskir

    06/11/2020, 1:38 PM
    there is
    actor { }
    c
    z
    +2
    • 5
    • 7
  • u

    ubu

    06/11/2020, 4:23 PM
    Hi there! Is there a way to update a
    value
    in
    StateFlow<Map<Id, T>>
    , so that current subscriber does not a receive this update? I have a particular use case from UI programming. Suppose that this
    T
    is
    String
    . We have a list of texts, that is rendered first in a text editor. This text is then edited by our user and we receive
    onTextChanged(id, text)
    event. We now need to sync this text change with our state:
    map[id] = text
    , but we do not need to render this state again, because UI already has it. Or maybe there is no way to resolve this problem with
    StateFlow
    ?
    z
    z
    • 3
    • 10
  • p

    Pacane

    06/11/2020, 4:45 PM
    Is there a way to use
    supervisorScope
    and pass it a parent supervisorJob? From the docs it says I can, but I don't see how I can pass it down
    z
    o
    b
    • 4
    • 3
  • r

    Rechee Jozil

    06/11/2020, 6:17 PM
    what's easiest way to "force" a suspension point without using delay function? I would like to force a suspension point but also not delay by any amount of time.
    o
    d
    j
    • 4
    • 10
  • g

    gotoOla

    06/11/2020, 8:15 PM
    Does anybody know about any article or such where I can read a bit more about the internals of kotlin? With internals I mean like... on a byte-code/language level. If I know about suspension points -> the continuation interface with resume etcetera -> The compiled java code which adds an object to the signature then where do I go next? If I have 1000 suspended coroutines (continuations), how is the scheduling for the "wake up" mechanism done on these?
    b
    • 2
    • 2
  • l

    Luis Munoz

    06/12/2020, 4:14 PM
    Can someone do a code walk through video of coroutines? I'm surprised that no open source project has done this, if their code is clean this would be a lot better than all the documentation they write
    g
    • 2
    • 2
  • y

    Yevhenii Nadtochii

    06/13/2020, 3:22 AM
    Hi all! I'm seeing into Channels\Coroutines in order to implement the next pattern: daemon-coroutine started in the Main thread processes messages from any other coroutines. I see it this way: 1) creating channel 2) launching background coroutine to iterate through channel 3) launching other coroutines that send to channel 4) close channel --> background coroutine terminates But it doesn't work, could anyone say where have I mistaken (code or may be concept itself) ?
    fun simpleChannelTest() {
        val channel = Channel<String>(capacity = Channel.Factory.UNLIMITED)
    
        val backgroundProcessor = MainScope().launch {
            for (str in channel) {
                println("$str has been processed")
            }
        }
    
        runBlocking(Dispatchers.Default) {
            val producers = launch {
                repeat(100) {
                    launch {
                        channel.send("str$it")
                    }
                }
            }
    
            println("producers have been created")
            producers.join()
            println("producers have done their work")
            channel.close()
            println("channel has been closed")
            backgroundProcessor.join() // ********************* I"M STUCK HERE
            println("backgroundProcessor coroutine has done its job") // ***************** UNREACHABLE
        }
    v
    • 2
    • 2
  • a

    Alexey Demedeckiy

    06/13/2020, 7:08 PM
    Hi! I am trying to implement some sort of event store / redux store using corutines in android application Here is the pseudocode:
    class Store {
      private val channel = Channel<Action>()
    
      suspend func dispatch(action: Action) {
        channel.send(action)
      }
    
      init {
        GlobalScope.launch {
          for (action in channel) {
            reduce(action)
            notifyObservers()
          }
        }
      }
    }
    Sadly, this code doesn't work - actions are not reducer. Small detail: If i will explicitly set Dispatchers.Main in init and in dispatch - it work, but defeats my purpose. My goal is to move action processing of main thread. 
    notifyObservers
     will build 
    Props
     for each active 
    ViewModel
     and publish.
    z
    v
    r
    • 4
    • 31
  • n

    nicholasnet

    06/14/2020, 5:15 AM
    Is there a way to covert Flux to Flow and Mono to coroutine equivalents without blocking.?
    z
    m
    • 3
    • 3
  • s

    Saurabh

    06/14/2020, 6:10 AM
    Do we have any replacement for actors yet. Can I achieve the same using maybe flows of some sort?
    o
    v
    • 3
    • 4
  • f

    fitken

    06/14/2020, 11:14 AM
    Hi everyone! I want to do async for API request in a suspend function like below:
    override suspend fun getMovieDetails(movieId: Int): LiveData<MovieEntity> {
            GlobalScope.launch {
                async {
                    try {
                        val movieData = mService.getMovieDetails(movieId)
                        mCache.updateMovie(movieData)
                        Rose.error("done") // *(2)*
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
    
            }
    
            Rose.error("run first") // *(1)*
            return Transformations.map(mCache.getMovie(movieId)) {
                return@map MovieEntity(....)
            }
        }
    I want (1) run first, then run (2). I managed to do that with GlobalScope, but GlobalScope is highly discouraged (I read this here https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html) I also searched on the internet and in this channel with keyword: async suspend function. But haven’t found any answer. Is there any other way to do that? Could anyone help me on this? Thank you so much.
    z
    l
    • 3
    • 8
  • a

    Alex Gotev

    06/14/2020, 4:44 PM
    Has somebody used TCP or UDP sockets with Kotlin Coroutines? AFAIK even if you wrap them to be coroutine friendly, they still block the underlying threads and I can't see any advantage over classical Thread Pool Executor.
    s
    • 2
    • 2
  • j

    jeggy

    06/14/2020, 5:23 PM
    If I'm creating a bunch of coroutines and doing a lot of work, should I be calling
    yield()
    every now and then all around in the code, so if any cancelation is requested that all my coroutines will cancel? And if so, how expensive is it to call
    yield
    ?
    o
    • 2
    • 13
  • d

    dimsuz

    06/14/2020, 8:29 PM
    I have a code like this:
    launch {
      try {
        myCoroutine() // throws exception when executed
      } catch (e: Exception) {
        println("caught $e")
      }
    }
    and instead of catching it crashes. But if I replace try/catch with
    runCatching { myCoroutine() }.exceptionOrNull()?.let { println("caught $e") }
    it catches and prints exception. Now,
    myCoroutine
    above involves calling android-related Retrofit library which has it's own coroutine adapters, so it might be doing some smarty stuff (debugger shows that
    continuation.resumeWithException()
    is called, maybe on different dispatcher), but I want to understand in general the difference between
    try/catch
    and `runCatching`: why can this situation happen and when I should use which approach to handling exceptions?
    o
    m
    • 3
    • 8
  • s

    Saurabh

    06/15/2020, 8:47 AM
    The
    combineLatest
    operator is deprecated for flows. Is there a way to achieve similar results with some other api in flow?
    a
    o
    g
    • 4
    • 4
  • g

    Gabriel Feo

    06/15/2020, 5:09 PM
    https://kotlinlang.slack.com/archives/CRJCTR5PD/p1592240915051900
    d
    s
    • 3
    • 5
  • k

    Koya Sivaji

    06/15/2020, 7:47 PM
    I am new to kotlin flows and trying to add Flows to one of my project and facing an issue while converting list of objects of one type to another as shown below. Basically, am not sure which operator to be used for this.
    
    //Repository - method return type is  Flow<List<HistoryEvent>>
    fun getHistoryEvents(): Flow<List<HistoryEvent>>
    
    //ViewModel - calling repository method and trying to convert data to List<AccessoryEvent>
    
    val accessoryEvents : LiveData<List<AccessoryEvent>>=  liveData{
                                                          repository.getHistoryEvents()
                                                           
                                                      // what operator to be used to convert from List<HistoryEvent> to List<AccessoryEvent>
                                                               
                                                            .collect()
                                                          }
    o
    • 2
    • 8
  • b

    Brendan Weinstein

    06/16/2020, 1:23 AM
    Is it a goal to coincide landing
    native-mt
    into master with kotlin 1.4? If not, what's the pulse check (3 vs 6 months away)? I am preparing an internal doc for evaluating kotlin multiplatform and a few coworkers have already asked this. Having stable multi-threaded coroutines for kotlin-native changes how folks perceive kmp viability.
    ➕ 8
    d
    e
    • 3
    • 2
  • s

    samuel

    06/16/2020, 5:09 PM
    Hi, I have a problem that i would like to solve using coroutines but haven’t found a successful way to do it. I have a while loop, that reads input from an input stream (bluetooth socket on android) until a specific number of words have been received. However, the while loop could run forever incase the specific number of words has not been sent (and the socket connection is still active). To mitigate this, i would like to have two operations running, one that runs a timeout (delay) and the other to do the actual work. These operations would run concurrently and i would be interested in getting the completion of the fastest operation. This way i can be sure that i would not wait for a result forever and i can handle the exception. One approach i tried was using withTimeout, but it would never really timeout (not sure why)
    withTimeout(20000) {
        try{
            while (true) {
                // read input from socket and exit while block when exception is thrown 
                // or expected data has been received   
            }
        }catch(e: Exception) {
            // Handle the exception here
        }
    }
    I also tried to use this, but the code within`scope.launch` was never executed but the timeout worked as expected
    val scope: CoroutineScope = CoroutineScope(Job() + <http://Dispatchers.IO|Dispatchers.IO>)
    withTimeout(20000){
        suspendCancellableCoroutine<String>{ continuation ->
    
            continuation.invokeOnCancellation {
                // Handle my exception here
            }
            
            scope.launch {
                while (true) {
                    // read input from socket and exit while block when exception is thrown 
                    // or expected data has been received   
                }
            }
        }
    }
    Could someone please help give me some pointers in what i might be missing or even perhaps a better way to approach this?
    z
    • 2
    • 10
  • l

    Luis Munoz

    06/16/2020, 5:14 PM
    I have a function that returns a flow witch emits only once, is there an operator that will call the method again giving an infinite flow until an error occurs? Maybe this a bad idea but seems fine to me. I have a function from a third party library that does polling for changes that returns a completeablefuture and I want to create a flow that emits on every change.
    b
    • 2
    • 2
  • r

    Rechee Jozil

    06/17/2020, 6:27 AM
    anyone try coroutines in their own subclass of LiveData? Lame that the
    CoroutineLiveData
    is hidden...
    g
    a
    • 3
    • 2
  • l

    louiscad

    06/17/2020, 8:16 AM
    Hello, I just had an idea to optimize the size of binaries using coroutines even further by reusing
    ContinuationImpl
    classes whenever possible. What do you think? Details here: https://youtrack.jetbrains.com/issue/KT-39644
    👀 2
    h
    w
    e
    • 4
    • 6
  • j

    jeggy

    06/17/2020, 10:29 AM
    fun main() = runBlocking {
        repeat(50) {
            launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                delay(5000L * it)
                println("Done $it")
            }
        }
    }
    Having some code like this. Is it possible to leak coroutines, if I were to just send the kill signal to this process?
    👀 1
    s
    z
    +2
    • 5
    • 6
  • g

    George Theocharis

    06/17/2020, 4:00 PM
    Hello all! Today came up with this weird exception. I have a custom presenter scope which i use to launch coroutines on. On java presenters an async method is exposed that get the scope as a parameter in order to be able to launch it in a kotlin file instead. Today I was writing some tests using mockk doing something like this:
    every { presenter.scope } returns TestCoroutineScope()
    and I was trying to verify in order some calls including the invokeAsync I mentioned. The exception I am getting is an abstract method error on newCoroutineContext that i cannot think of a solution. The code works, the test not. If you also debug it also works correctly until its time to return to the java side. Sorry for the wall its a bit complicated and haven’t seen it previously. Ps i am using dispatchers.setMain and the coroutines test dependency.
    z
    • 2
    • 3
  • i

    itnoles

    06/17/2020, 7:27 PM
    Do I need to have continuation.isCancelled inside suspendCancellableCoroutine for okhttp?
    d
    • 2
    • 8
  • l

    Luoqiaoyou

    06/18/2020, 10:26 AM
    I upgrade kotlin version to 1.4-m2,and use coroutines version: 1.3.7-native-mt-1.4-M2. But i got a error:
    Unresolved reference: newSingleThreadContext
    in iosMain sourceSet. Was it removed in this version?
    a
    • 2
    • 1
  • s

    Slackbot

    06/18/2020, 2:41 PM
    This message was deleted.
    l
    a
    e
    • 4
    • 11
  • b

    Brandon Trautmann

    06/18/2020, 4:58 PM
    Messing around with Room for the first time, and wondering what you all think about this usage:
    viewModelScope.launch {
    customerRepo.customer(customerUid) // Returns a `Flow<Customer>`
      .combine(controllerRepo.controllersForCustomer(customerUid)) { customer, controllers ->
        CustomerWithControllers(customer, controllers)
      }
      .collect { customerWithControllers ->
        internalState.value = State.Loaded(customerWithControllers)
      }
    }
    This works just fine, but when I go to delete a
    customer
    , the deletion cascades to the
    controllers
    and what you end up with is a new
    CustomerWithControllers
    with empty controllers because the
    customer
    Flow
    last emission was the customer that was just deleted. I solved this by holding onto the
    Job
    returned by
    launch
    , and when I go delete a customer, I basically cancel that
    Job
    , delete the customer, and then execute a function that checks for the existence of any customer and if one doesn't exist, brings the user to a FTUX screen. Is this a decent way of handling this? It'd be nice if
    Room
    had some way to emit an
    Empty
    token or something to indicate the table is empty 🤔
    r
    • 2
    • 4
  • k

    katokay

    06/21/2020, 12:09 PM
    Cross posting as it also pertains to coroutines and frozen state. https://kotlinlang.slack.com/archives/C3SGXARS6/p1592674187016400
    • 1
    • 1
Powered by Linen
Title
k

katokay

06/21/2020, 12:09 PM
Cross posting as it also pertains to coroutines and frozen state. https://kotlinlang.slack.com/archives/C3SGXARS6/p1592674187016400
Found a combination that worked. Whew, some gymnastics getting ramped up on strict-mode.
View count: 9