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

    Florian

    12/02/2020, 9:32 AM
    Lets say I have a sealed class
    A
    with 2 subclasses
    B
    and
    C
    . Can I combine a
    Flow<B>
    and a
    Flow<C>
    to a
    Flow<A>
    ?
    m
    l
    • 3
    • 31
  • p

    pablisco

    12/02/2020, 10:18 AM
    Hello everyone! I was wondering if someone has tried to implement something like this:
    fun <T> loopFlow(initial: T, f: suspend (T) -> Flow<T>): Flow<T>
    The idea being that the
    initial
    value is emitted once and then
    f
    is applied recursively. And then finish the flow when cancelled or when an empty flow is produced (duh). I’ll post in thread what I’ve tried so far without much luck…
    g
    l
    • 3
    • 21
  • l

    Lilly

    12/02/2020, 2:19 PM
    Hi, I have a function that I want to suspend until I resume it manually from another function:
    private suspend fun sendPacketWithAcknowledgement(packet: RequestPacket) {
            try {
                withTimeout(PACKET_CONFIRMATION_TIMEOUT) {
                    sendPacket(packet.bytes)
                }
                // Wait here until ack packet received
                // mutex.lock() // I thought this will suspend the code here and on mutex.unlock() it will resume here
            } catch (e: TimeoutCancellationException) {
                // do sth.
            }
        }
    On caller site:
    sendPacketWithAcknowledgement(StartCommunication()) // should be sequential
    isCommunicationEstablished = true
    The caller code should behave sequential, so that
    isCommunicationEstablished = true
    is only processed, when the ack packet is received and the suspension is resumed manually. I thought mutex would fit here but I guess I didn't use it the right away. It's a bluetooth classic scenario btw. So does someone know how I can achieve this behavior?
    o
    • 2
    • 2
  • s

    Saul Wiggin

    12/02/2020, 4:07 PM
    What does getMyData().collect do where getMyData is a flow object?
    b
    • 2
    • 1
  • b

    bbaldino

    12/02/2020, 8:34 PM
    Is there a way to wait for an element from a flow with some timeout? Like to emit either 1) whatever is sent on the wrapped flow or 2) something else if the wrapped flow doesn't produce an element within some time period?
    b
    • 2
    • 9
  • n

    Nikky

    12/03/2020, 1:28 PM
    can i poll all items of a buffered channel as a list ? my intent is to ingest events into a buffered channel and at a set rate bulk insert all that are currently in the buffered channel is that the correct way to handle this or is there cleaner constructs provided by coroutines that i am missing ? one of the requirements is that inserting events should cause backpressure
    d
    • 2
    • 5
  • e

    Erik

    12/03/2020, 5:47 PM
    Would you please help me with the following? I want to test that the buffer size of my
    MutableSharedFlow<T>(replay = 0, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
    equals
    1
    (in reality it's variable). I can't figure out how to get this working in a unit test: every time I emit something it is immediately collected (I use Turbine to
    test
    the flow). I basically want to emit 2 items and verify that only the last one is collected, the oldest is dropped.
    👍 1
    • 1
    • 5
  • n

    Nikky

    12/04/2020, 11:44 AM
    how can i combine a ticker channel and a flow so that on either element in flow or a tick from the channel it emits to the combined flow? is combine the correct operator there?
    l
    • 2
    • 2
  • f

    Florian

    12/04/2020, 1:12 PM
    I have a question regarding this article: https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad My question: If the repository method would not contain
    doSomeOtherWork
    , we could also switch to the `applicationScope`/`externalScope` in the ViewModel directly, right?
    j
    m
    • 3
    • 11
  • t

    Tolriq

    12/05/2020, 10:28 AM
    Is there a proper way to "merge" multiple jobs from flow
    launchIn
    to allow simple cancellation without cancelling the scope / job that is used in the
    launchIn
    call? Currently saving each jobs separately and cancelling them one by one.
    t
    b
    +2
    • 5
    • 12
  • f

    Florian

    12/05/2020, 2:16 PM
    Is there something wrong with the design of this method? It's both a
    suspend fun
    but also returns a Flow. And the first line can't be caught like this because it's not inside the Flow.
    suspend fun getChatUserFlow(uid: String): Flow<ChatUser?> {
            val results = userCollection.whereEqualTo(FieldPath.documentId(), uid).get().await()
            return if (!results.isEmpty) {
                results.documents[0].reference.asFlow<ChatUser>()
            } else {
                flowOf(null)
            }
        }
    g
    • 2
    • 3
  • v

    v0ldem0rt

    12/06/2020, 3:02 AM
    I am trying to write a suspend function that can listen to cancellation of continuation, and invoke a suspended callback. Here is what I am looking at:
    suspend fun <T> PreparedStatement.withCancellation(callback: suspend () -> T): T {
        val stmt = this
        suspendCancellableCoroutine { cont ->
            cont.invokeOnCancellation { 
                stmt.cancel()
            }
        }
    
        return callback()
    }
    z
    • 2
    • 1
  • f

    Florian

    12/06/2020, 8:35 PM
    Exceptions that happen inside a callback used inside a
    callbackFlow
    can not be caught with the
    catch
    operator?
    a
    • 2
    • 6
  • v

    v0ldem0rt

    12/07/2020, 2:43 AM
    Is there a way to register a cancellation listener on a coroutine scope without doing
    suspendCancellableCoroutine
    so that if the scope gets cancelled I can close my DB statements
    b
    • 2
    • 3
  • f

    Florian

    12/07/2020, 10:03 AM
    What happens if you combine 2 Flows and one of them throws an exception? Will it be caught in a
    catch
    operator I add on the resulting (combined) Flow?
    ✔️ 1
    l
    b
    • 3
    • 14
  • r

    Ray

    12/07/2020, 3:46 PM
    Is their a need to wrap a DAO Room coroutine function with a withcontext(Dispatcher.io) block. Example
    Query()
    suspend fun getUser():User
    Repository
    suspend fun getUserFromDb():User {
    return withcontext (<http://dispatcher.IO|dispatcher.IO>) {return data.getUser()}
    }
    k
    m
    • 3
    • 3
  • z

    zak.taccardi

    12/07/2020, 5:50 PM
    How can an initial value be loaded from a
    suspend
    function using something similar to
    .scan(..)
    with a
    SharedFlow
    ?
    .scan(loadInitialValueAsynchronously()) { .. }
    I’m effectively trying to replace an
    actor
    with a
    SharedFlow
    .
    Untitled
    • 1
    • 2
  • s

    Slackbot

    12/08/2020, 9:08 AM
    This message was deleted.
    ✔️ 1
    w
    f
    • 3
    • 3
  • t

    Tolriq

    12/08/2020, 10:02 AM
    Just a simple confirmation. The collect of the stateflow in following code will ran in whatever scope the created flow is collected and will be properly cancelled when the collecting flow is cancelled?
    fun <T> StateFlow<T>.withPrevious(): Flow<Pair<T?, T>> {
        return flow {
            var previous: T? = null
            this@withPrevious.onEach {
                emit(Pair(previous, it))
                previous = it
            }.collect()
        }
    }
    c
    • 2
    • 4
  • s

    Sourabh Rawat

    12/08/2020, 12:37 PM
    fun main() = runBlocking {
    
        val httpClient = HttpClient {
            install(Logging) {
                level = LogLevel.ALL
            }
    
            @OptIn(KtorExperimentalAPI::class)
            install(WebSockets)
    
            expectSuccess = false
    
            install(JsonFeature) {
                @OptIn(KtorExperimentalAPI::class)
                acceptContentTypes = listOf(ContentType("application", "json-rpc"))
                serializer = KotlinxSerializer()
            }
        }
        val wss =httpClient.webSocketSession(method = HttpMethod.Get, host = "127.0.0.1", port = 6800, path = "/jsonrpc")
        wss.close()
    }
    this does not stop the program. what am I doing wrong?
    s
    j
    +2
    • 5
    • 10
  • t

    Tash

    12/08/2020, 6:52 PM
    Trying out a few ways to throttle API GET requests. The `debounce`/`sample` operators for 
    Flow
     don’t work as desired, so what I need is more of a 
    throttleFirst
     . Tried with using 
    async
     and returning 
    null
     when the request should be throttled:
    class ApiClient {
    
        private var deferredLoad: Deferred<Result>? = null
    
        suspend fun load(throttleMillis: Long = 300): Result? {
            return coroutineScope {
                if (deferredLoad?.isCompleted != false) {
                    async {
                        val result = /** make GET API call **/
                        delay(throttleMillis)
                        result
                    }
                    .apply { deferredLoad = this }
                    .await()
                } else {
                    null
                }
            }
        }
    }
    Is this approach recommended? Finding it a little weird to hold on to a 
    var
     of 
    Deferred
     , thinking it might need a 
    Mutex
    . Wondering if there’s a more elegant approach that others have found?
    a
    • 2
    • 1
  • s

    Shan

    12/09/2020, 2:06 AM
    Hello. Does anyone know why, when using
    .asSingle()
    on a
    Deferred<T>
    from the
    kotlinx-coroutines-rx2
    library, why the
    coroutineContext
    I pass into
    .asSingle()
    can't contain a Job?
    s
    • 2
    • 3
  • k

    kevinherron

    12/09/2020, 12:44 PM
    when adapting a callback API to suspending is there any point in using
    suspendCancellableCoroutine
    instead of
    suspendCoroutine
    when there is no way to propagate cancellation to the adapted API and no action to run via
    CancellableContinuation::invokeOnCancellation
    ?
    g
    b
    • 3
    • 3
  • n

    Nikola Milovic

    12/09/2020, 3:23 PM
    Hey guys, not sure if this is big enough for slack, how can I run a suspending coroutine inside another suspending coroutine? I have this callback function in my repository
    override suspend fun saveConfession(text: String): SaveConfessionResponse = suspendCoroutine {cont ->
            val confessionToSave = ConfessionDataModel(text)
            val call = newConfessionService.saveConfession(confessionToSave)
            call.enqueue(object : Callback<SaveConfessionResponse>{
                override fun onResponse(call: Call<SaveConfessionResponse>, response: Response<SaveConfessionResponse>) {
                   cont.resume(response.body()!!)
                }
    
                override fun onFailure(call: Call<SaveConfessionResponse>, t: Throwable) {
                    cont.resumeWithException(t)
                }
            })
        }
    
    And I am trying to call it from my useCase object
    
       suspend fun execute(text: String): Result = suspendCoroutine{ cont->
            try {
                val response = confessionRepository.saveConfession(text)
                when (response.status) {
                    200 -> Result.Success(response.id, 200)
                    400 -> Result.Error(null)
                    500 -> Result.Error(null)
                    else -> Result.Error(null)
                }
            } catch (e: Exception) {
                return Result.Error(e)
            }
        }
    / But i cannot call saveConfession outside of coroutine body, can I somehow get the scope that the execute function was called from?
    m
    m
    • 3
    • 10
  • c

    Colton Idle

    12/09/2020, 8:11 PM
    New to coroutines and flow but does anyone have an example of doing an edittext debounce in flow? The few examples from my search look a LOT lengthier than I think it should be compared to rxjava. Any good resource anyone has found in the past?
    a
    • 2
    • 2
  • g

    Guillermo Alcantara

    12/09/2020, 10:47 PM
    Hello, can anyone help me understand the risks associated with using
    ExperimentalCoroutinesApi
    functions in prod for a library? Should I surface that to my users? If I understand correctly, it means it will be binary compatible (unlike
    FlowPreview
    ). So the only issue is that at some point I might need to change code. But the AAR will be fine using a future version of the library?
    m
    x
    • 3
    • 2
  • a

    asad.awadia

    12/10/2020, 12:09 AM
    what is the best way to simulate an arrayblockingqueue/channel ? MutableSharedFlow? I want to have a place to put items in such that only 1 of my 64 coroutines receive them - simple use case - items come in via a blocking http server [i.e. will need runBlocking to call any suspend methods] - I want to add it to the queue and have the coroutines in the background fetch them in chunks if possible
    z
    i
    • 3
    • 6
  • a

    Animesh Sahu

    12/10/2020, 1:47 PM
    Support suspend test functions Why's it still not implemented in stdlib 🤔 There should be a runBlocking or runBlockingTest, for testing coroutine based code in commonTest module...
    c
    • 2
    • 1
  • l

    liminal

    12/10/2020, 5:05 PM
    Not to reinvent the wheel, what Flow operators are you all using to accomplish offline logic (return from local persistence if available, or hit api, cache in local persistence and return).
    i
    • 2
    • 2
  • g

    Gilles Barbier

    12/10/2020, 6:13 PM
    Hello, I'm writing a worker using kotlin, I receive messages from a channel (from a queuing system) - those messages trigger the processing of tasks that I do not manage (user can add its own). To run n job in parallel, I have n coroutines constantly pulling from this channel and running the jobs. I did some tests with CPU intensive jobs (with plain not suspended java) and apparently it works - jobs are processed in parallel - but I do not understand how/why ?! Do you have an explanation ?
    • 1
    • 1
Powered by Linen
Title
g

Gilles Barbier

12/10/2020, 6:13 PM
Hello, I'm writing a worker using kotlin, I receive messages from a channel (from a queuing system) - those messages trigger the processing of tasks that I do not manage (user can add its own). To run n job in parallel, I have n coroutines constantly pulling from this channel and running the jobs. I did some tests with CPU intensive jobs (with plain not suspended java) and apparently it works - jobs are processed in parallel - but I do not understand how/why ?! Do you have an explanation ?
I think I've understood: a new thread is used for each job, while there is one available in an underlying thread pool.
View count: 2