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

    dave08

    02/10/2020, 5:15 PM
    Is it on purpose that
    Flow
    has
    singleOrNull
    but not
    firstOrNull
    ?
    d
    b
    • 3
    • 7
  • e

    Erik

    02/11/2020, 3:54 PM
    I'm having issues testing expected exceptions in coroutines on Android. Full MWE in the attached code snippet. As far as I understand is that when a new coroutine is launched from a unit test, even if that indirectly happens on the
    TestCoroutineDispatcher
    or
    TestCoroutineScope
    , then any exceptions are swallowed (although the stack traces are printed). What is the general pattern to work with expected exceptions in unit tests and coroutines on Android?
    Untitled
    a
    • 2
    • 9
  • j

    Jiri Bruchanov

    02/11/2020, 9:51 PM
    Hi, anyone who could help me with
    'More than one file was found with OS independent path 'META-INF/kotlinx-coroutines-core.kotlin_module'
    ?
    o
    • 2
    • 5
  • v

    voben

    02/11/2020, 11:43 PM
    How do I return a value from a flow? Trying to return the myString value
    suspend fun doSomething(): String {
       val myFlow = flow { emit("hello") }
       myFlow.collect { myString ->
            return myString
       }
    }
    m
    s
    • 3
    • 8
  • m

    mng

    02/12/2020, 12:51 AM
    Hi guys, I’m still pretty new to Coroutines and was wondering if anyone can let me know if I’m on the right track for what I want. Problem: I’m currently building out an Android application and I have several screens that require the User’s Location. This application can have multiple Activities/Fragments in its backstack. If the user changes their location on a screen, I would want every screen in the backstack to get that updated location object as well. Question: Looking into
    Flows
    , is a
    channelFlow
    what I need for my particular use-case? There would be one singular source-of-truth that multiple call sites will be subscribing to for the User’s location and would be a cold stream as the location would only be updated based on a method invocation.
    l
    • 2
    • 7
  • a

    Abhishek Bansal

    02/12/2020, 4:49 PM
    Hello, I am trying to concat two flows in a way that I get results sequentially when I collect on it
    flowOf(
     remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
      .catch { error -> Timber.e(error) },
     remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
    ).flattenConcat().collect {
    Timber.i("Response Received")
    }
    my expectation here was that I will get first result first and then second after sometime as response comes from server. But the problem here is collect only gets called after server returns result.
    l
    • 2
    • 5
  • a

    Arkadii Ivanov

    02/12/2020, 9:18 PM
    Hello, I'm playing with a custom
    CoroutineDispatcher
    implementation using this implementation as a reference: https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/kotlinx-coroutines-rx2/src/RxScheduler.kt However
    Delay
    interface is marked as
    InternalCoroutinesApi
    . Is there a good way to implement delaying?
    ➕ 1
    l
    v
    • 3
    • 3
  • l

    LastExceed

    02/12/2020, 11:45 PM
    I am doing my first steps with coroutines. I wrote a simple multi-client echo server using ktor, can someone please review my code and point out potential spaghetti?
    import io.ktor.network.selector.ActorSelectorManager
    import io.ktor.network.sockets.*
    import kotlinx.coroutines.*
    import <http://kotlinx.coroutines.io|kotlinx.coroutines.io>.*
    import <http://java.net|java.net>.InetSocketAddress
    import java.nio.channels.ClosedChannelException
    
    suspend fun main() {
    	val echoServer = EchoServer()
    
    	supervisorScope {
    		launch {
    			echoServer.start()
    		}
    
    		while (readLine() != "exit") {
    			println("unknown command")
    		}
    		println("stopping server")
    		echoServer.stop()
    	}
    }
    
    class EchoServer {
    	private val listener: ServerSocket =
    		aSocket(ActorSelectorManager(<http://Dispatchers.IO|Dispatchers.IO>)).tcp().bind(InetSocketAddress(12345))
    	private val clients = mutableListOf<Socket>()
    
    	suspend fun start() {
    		coroutineScope {
    			while (true) {
    				val client =
    					try {
    						listener.accept()
    					} catch (_: ClosedChannelException) {
    						break
    					}
    				launch {
    					handleClient(client)
    				}
    			}
    		}
    	}
    
    	private suspend fun handleClient(client: Socket) {
    		println("new client connected")
    		clients.add(client)
    		val reader = client.openReadChannel()
    		val writer = client.openWriteChannel(true)
    		while (true) {
    			val message = reader.readUTF8Line() ?: run {
    				println("client disconnected")
    				return
    			}
    			writer.writeStringUtf8("$message\n")
    		}
    	}
    
    	fun stop() {
    		listener.close()
    		clients.forEach {
    			it.close()
    		}
    		clients.clear()
    	}
    }
    o
    g
    • 3
    • 11
  • c

    CLOVIS

    02/13/2020, 12:46 PM
    Is the order preserved in a Flow? Is there a way to tell it to run lambdas (
    map
    , etc) in parallel and send elements as soon as possible, even if the order is lost?
    d
    • 2
    • 4
  • t

    taer

    02/13/2020, 3:05 PM
    Flow question. the
    sample
    operation is almost exactly what I want. Except for that small warning
    Note that the latest element is not emitted if it does not fit into the sampling window.
    I want to collapse elements(just like sample does), but the last element at any time is kinda important. Any pointers?
    • 1
    • 1
  • v

    vineethraj49

    02/13/2020, 7:59 PM
    what is the difference between the
    block: suspend () -> T
    and
    block: suspend CoroutineScope.() -> T
    types?
    o
    e
    l
    • 4
    • 4
  • g

    getabu

    02/13/2020, 9:21 PM
    I need help with since Coroutine never calls API after job either cancelled or pending. Details: https://stackoverflow.com/questions/60216513/coroutine-never-calls-api-after-job-either-cancelled-or-pending
    m
    • 2
    • 1
  • s

    svenjacobs

    02/14/2020, 8:39 AM
    What is the best approach of starting a long running computation inside a
    CoroutineScope
    that keeps on running even if the scope is cancelled and if another (new) scope is accessing the same function/computation, the already computed value should be returned? Sounds like a job for a
    ConflatedChannel
    , right? I tried something with
    Deferred
    but the code (test code!!) is far from beautiful:
    var result: Deferred<Int>? = null
    
    fun longComputationAsync(): Deferred<Int> {
        result = result ?: GlobalScope.async {
            println("longComputation")
            delay(1000)
            1337
        }
        return result!!
    }
    
    val scope1 = CoroutineScope(Dispatchers.Default)
    scope1.launch {
        println("scope 1")
        println(longComputationAsync().await())
    }
    scope1.cancel()
    
    val scope2 = CoroutineScope(Dispatchers.Default)
    val job = scope2.launch {
        println("scope 2")
        println(longComputationAsync().await())
    }
    
    runBlocking {
        job.join()
    }
    m
    b
    u
    • 4
    • 8
  • c

    Chills

    02/14/2020, 11:16 AM
    so basically coroutinecontext have a scope and these are coroutinescope which provides lifecycle to coroutine.
    d
    • 2
    • 1
  • e

    Evan R.

    02/14/2020, 3:52 PM
    message has been deleted
    a
    • 2
    • 1
  • c

    CLOVIS

    02/15/2020, 3:48 PM
    I'm searching for a data structure that allows a consumer to request for some data one by one (eg. A function
    next()
    or something similar), and from one-to-many producers to add new data to it. That sounds awfully similar to what a Channel is, however from my understanding the consumer·s of a channel act as soon as an element is produced, rather than when they want to? Basically I'm searching for a way to have the client decide when new elements are produced, and that data structure would have some kind of buffer of size
    n
    so the client could almost always get the data instantaneously, and the producer·s would get to work immediately when the buffer gets too small to add new elements.
    d
    k
    s
    • 4
    • 6
  • a

    Ahmed Ibrahim

    02/15/2020, 9:30 PM
    What's the equivalent of Rx's
    PublishProcessor
    in the Coroutines world?
    s
    b
    • 3
    • 5
  • s

    Saket Poddar

    02/17/2020, 9:02 AM
    Hi All, it might seem trivial, but I wanted to ask, shall cancel CoroutineScope in ViewModel$onCleared or shall I cancel in Activity$onDestroy. What is recommended???
    d
    • 2
    • 4
  • g

    gsala

    02/17/2020, 9:17 AM
    Hey. I have an Rx library I use to connect to a BLE device. This library has this function:
    fun connect(bluetoothDevice: BluetoothDevice) : Observable<RxBleConnection>
    . The reason this returns an
    Observable
    instead of a
    Single
    is that the life-cycle of the
    Observable
    is tied to the connection. So this observable will only ever emit one item, but it will stay alive without completing so the connection stays alive until we dispose. I want to wrap this to use coroutines instead. I'm thinking about having a function like
    suspend fun connect(bluetoothDevice : BluetoothDevice) : RxBleConnection
    , Any ideas on how to handle the life-cycle of the Observable? If I just use
    connectObservable.awaitFirst()
    it will take the first value, and dispose, which will stop the connection.
    l
    • 2
    • 1
  • m

    myanmarking

    02/17/2020, 1:13 PM
    unless you change the dispatcher of emmit
    d
    • 2
    • 19
  • r

    rkeazor

    02/17/2020, 3:06 PM
    will channelFlow or callbackFlow be reaching Stable anytime soon?
    d
    b
    a
    • 4
    • 4
  • m

    Michael Friend

    02/17/2020, 5:26 PM
    Is there a way to implement dynamic timeout for a coroutine? Basically if I'm running callable A and B in parallel with some timeout t, I want to extend the timeout of callable A based on the response from callable B (which should be faster). Would I just have to avoid using withTimeout and instead keep track of the time and cancel manually?
    e
    • 2
    • 2
  • r

    Robert Jaros

    02/18/2020, 1:59 PM
    Should I use
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
    when using
    ConcurrentHashMap
    inside a suspending function?
    d
    s
    k
    • 4
    • 6
  • b

    Brendan Weinstein

    02/18/2020, 7:22 PM
    Anyone have tips for installing java 1.6 on a mac to run tests from the coroutines repo?
    k
    • 2
    • 5
  • m

    Michael Friend

    02/18/2020, 8:35 PM
    How do you guys usually handle exceptions in coroutines while still propagating cancelations? It always feels a little clunky and with too much boiler plate since coroutines are built to use exceptions but kotlin doesnt have checked exceptions so you usually have to do
    try {
        exceptionalMethod()
    catch (e: Exception) {
        if (e is CancellationException) {
           throw e
        }
        // handle other exceptions 
    }
    Would it be worth writing a some sort of top level function similar to runCatching that does the above? Or are there cleaner solutions?
    k
    s
    b
    • 4
    • 14
  • m

    Mohamed Ibrahim

    02/18/2020, 10:43 PM
    how do I switch between dispatchers using
    async
    and
    await
    ?
    z
    b
    • 3
    • 4
  • j

    JoakimForslund

    02/19/2020, 1:54 PM
    Did something change with iosArm32 for
    Expected property 'PLATFORM_DISPATCHER' has no actual declaration in module 
    The following declaration is incompatible because return type is different:
        internal actual var PLATFORM_DISPATCHER: [ERROR : CoroutineDispatcher]
    I can't compile my iosArm32 module after updating to 1.3.61
    • 1
    • 3
  • m

    Mohamed Ibrahim

    02/19/2020, 2:07 PM
    Could anyone explain simply what the responsiblity of the
    continuation
    object which is passed around with suspend functions?
    d
    • 2
    • 1
  • s

    Sanket Mehta

    02/19/2020, 2:45 PM
    How do I print all the handler names with below program? Currently, it's only printing 0th handler name and waiting for it to finish:
    import kotlinx.coroutines.GlobalScope
    import kotlinx.coroutines.async
    import kotlinx.coroutines.runBlocking
    import java.util.stream.IntStream
    
    fun main() {
        runBlocking {
            val asyncs = IntStream.range(0, 6).mapToObj {
                GlobalScope.async {
                    handleData("handler-$it")
                }
            }
            asyncs.forEach {
                runBlocking {
                    it.await()
                }
            }
        }
    }
    
    private fun handleData(handlerName: String) {
        println(handlerName)
        while (true) {
        }
    }
    Current output: handler-0 Expected output: handler-0 handler-1 handler-2 handler-3 handler-4 handler-5
    a
    k
    • 3
    • 3
  • m

    myanmarking

    02/19/2020, 3:56 PM
    hey guys. is there any ETA for StateFlow releasE ?
    e
    • 2
    • 1
Powered by Linen
Title
m

myanmarking

02/19/2020, 3:56 PM
hey guys. is there any ETA for StateFlow releasE ?
e

elizarov

02/19/2020, 5:42 PM
No specific eta yet.
View count: 6