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

    ursus

    01/02/2022, 4:04 PM
    Hey, Im writing a adapter for android sharedpreferences listener into flow
    private fun SharedPreferences.onSharedPreferenceChangedFlow(): Flow<String> {
        return callbackFlow {
            val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
                trySend(key)
            }
            registerOnSharedPreferenceChangeListener(listener)
            awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
        }
    }
    seems to work, however I do know there is one nasty behavior of the
    SharedPreferences.registerOnSharedPreferenceChangeListener
    , that it only keeps weak references, so the listener might get gc-ed so I need to hard reference the listener How would I turn it into a field? Or rather, I think I need a proper CallbackFlow subclass, not just use the builder, right? And looking at sources, everything is private / internal api
    t
    a
    • 3
    • 6
  • l

    liminal

    01/03/2022, 12:04 AM
    Hey, how do you observe SharedFlow in Jetpack Compose? I am currently observing StateFlow in Compose like so: val state by myViewModel.myStateFlow.observeAsState() but was wondering what the right thing to do is with SharedFlow
    f
    m
    • 3
    • 3
  • a

    Astronaut4449

    01/03/2022, 6:15 AM
    Is Ktor doing it all wrong? Hoping to find some answers/opinions on this channel. https://kotlinlang.slack.com/archives/C0A974TJ9/p1640968234268400
    s
    n
    • 3
    • 4
  • f

    Florian Walther (live streaming)

    01/03/2022, 3:11 PM
    I use the following code to create a fake implementation of a countdown timer based on Coroutines. Can someone tell me if this will be exact or if I need to calculate the time difference in some other way? (see thread)
    👀 1
    d
    n
    c
    • 4
    • 10
  • u

    ursus

    01/03/2022, 9:47 PM
    Why would I not always use Dispatchers.Main.immediate (over the nonimmediate)?
    👀 1
    b
    f
    m
    • 4
    • 5
  • f

    farzad

    01/04/2022, 9:32 AM
    I have a callback based API which I tried to convert it into a hot flow using callbackFlow builder. Would you mind suggesting how to write a unit test which ensures that the API is correctly converted to a hot cold flow? Here is my StackOverflow question: https://stackoverflow.com/questions/70576533
    j
    u
    • 3
    • 6
  • t

    thana

    01/04/2022, 10:50 AM
    hi, i just read https://maxkim.eu/things-every-kotlin-developer-should-know-about-coroutines-part-2-coroutinescope which says that one shouldn't implement the
    CoroutineScope
    interface anymore. unfortunately it doesn't say anything about the WHY despite using the builder function would be more straightforward. why is it more straightforward?
    n
    • 2
    • 5
  • n

    Norbi

    01/04/2022, 12:51 PM
    Hello, Is there a mature example of creating a
    java.lang.reflect.Proxy
    for a Kotlin interface with
    suspend
    methods? (I would call the proxy methods only from Kotlin code.) Thanks.
    j
    y
    • 3
    • 7
  • r

    Rak

    01/04/2022, 2:49 PM
    Hi, I am writing an android instrumentation test to test one of my fragments. The fragment uses a (real) viewmodel and I have declared mocks for it to use. The issue is one of these mocks (a repository class) has a suspend function and I am not sure what to do in the test.
    m
    • 2
    • 2
  • a

    Aslo

    01/04/2022, 6:30 PM
    I have a object list that is processed using parallelstream. How can I migrate this to corroutine?
    b
    j
    • 3
    • 3
  • e

    Elliot Barlas

    01/04/2022, 6:39 PM
    Is anyone here familiar with ktor raw sockets? I'm seeing a strange behavior when I employ ktor raw sockets at scale and I'm hoping someone might be able to help.
    n
    • 2
    • 2
  • v

    Victor Cardona

    01/04/2022, 11:37 PM
    Hello everyone! I have a question about best practices when using coroutines in a Spring MVC application. We are stuck on a version 2.3 for now and don't have access to coroutine support in the controller. So I use runBlocking in my controller methods, and call suspending functions in my services. Ultimately this will lead to blocking calls to another service. Is it better to run all coroutines including the one created by the runBlocking call with Dispatchers.IO by specifying it in the controller or should I just have the coroutines that make the blocking calls specify the dispatcher? I'm worried about testability mainly. Thanks!
    j
    • 2
    • 1
  • u

    ursus

    01/05/2022, 4:28 AM
    Is it possible to tweak channel settings in callback or channelflow? or is it hardcoded to
    BUFFERED
    and expected for consumers to use
    buffer
    operator?
    b
    j
    n
    • 4
    • 56
  • p

    Paul Woitaschek

    01/05/2022, 9:32 AM
    It seems that runTest is somehow broken with shared flows:
    private suspend fun testBody(scope: CoroutineScope) {
        val value = MutableStateFlow(1)
        val sharingJob = Job()
        val flow = value.shareIn(scope + sharingJob, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
        check(flow.first() == 1)
        value.value = 2
        check(flow.first() == 2)
        sharingJob.cancel()
      }
    
      @Test
      fun withRunBlockingTest() = runBlockingTest {
        testBody(this)
      }
    
      @Test
      fun withRunTest() = runTest {
        testBody(this)
      }
    This passes with runBlockingTest but fails with runTest. It is possible to fix it by adding a runCurrent before calling flow.first a second time but I think thats not how it’s supposted to be and makes me very uncomfortable writing tests without having a runCurrent between every single line
    j
    • 2
    • 6
  • f

    Florian Walther (live streaming)

    01/05/2022, 12:25 PM
    How would you test this countdown timer based on coroutines? What can I use as the time source because I can't use
    SystemClock.elapsedRealtime
    in a test.
    l
    • 2
    • 8
  • j

    janvladimirmostert

    01/05/2022, 8:41 PM
    Is it possible to get hot flows or are all flows cold and I should rather use a channel? Use-case: logging When I have a 10k concurrent things happening and they are all logging I want to throw the log line on a "channel" and not block the call-site until the log is completed Then on a consumer side, I want to process the incoming logs in batches, grab a 100 at a time or until the "channel" is empty and do a single println for example or a single POST if it's going to an external logging server
    c
    g
    • 3
    • 6
  • f

    Florian Walther (live streaming)

    01/06/2022, 12:05 PM
    In my following code, if
    countDownInterval
    is 0 I want to skip the loop and just delay until the time is over. The problem is that delay is inexact (that's why I do the comparison with the SystemClock time). How could I achieve a (somewhat) exact delay?
    s
    j
    • 3
    • 12
  • j

    janvladimirmostert

    01/06/2022, 10:42 PM
    I'm wrapping java.nio.channels.AsynchronousFileChannel with a callbackFlow to convert an asynchronous File reader into a flow. Is there a better way of doing this or anything that I can improve on this implementation?
    class FileFlow(private val uri: String) {
    
    	private data class FileBaton(
    		val fileChannel: AsynchronousFileChannel,
    		val flow: ProducerScope<ByteArray>,
    		val buffer: ByteBuffer,
    		val position: Long,
    		val handleError: (message: String, e: Throwable?) -> Unit = { message, e ->
    			flow.cancel(message, e)
    			runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
    				fileChannel.close()
    			}
    		}
    	)
    
    	fun read(bufferSize: DataSize): Flow<ByteArray> = callbackFlow {
    
    		val path = Path.of(uri)
    		val baton = FileBaton(
    			buffer = ByteBuffer.allocate(bufferSize.B),
    			fileChannel = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    				AsynchronousFileChannel.open(path, StandardOpenOption.READ)
    			},
    			flow = this,
    			position = 0,
    		)
    
    		baton.fileChannel.read(
    			baton.buffer,
    			baton.position,
    			baton,
    			object : CompletionHandler<Int, FileBaton> {
    				override fun completed(read: Int, baton: FileBaton) {
    					if (read > 0) {
    						trySendBlocking(
    							baton.buffer.array().sliceArray(0 until read)
    						).onFailure { e ->
    							baton.handleError(e?.message ?: "", e)
    						}
    
    						baton.buffer.rewind()
    						baton.fileChannel.read(
    							baton.buffer,
    							baton.position + read,
    							baton.copy(
    								position = baton.position + read
    							),
    							this
    						)
    					} else {
    						baton.flow.channel.close()
    						runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
    							baton.fileChannel.close()
    						}
    					}
    				}
    
    				override fun failed(e: Throwable?, baton: FileBaton) {
    					baton.handleError(e?.message ?: "", e)
    				}
    			}
    		)
    		awaitClose {
    
    		}
    	}
    }
    FileFlow("/home/.../blah.txt").read(250.kB).collect {
       print(String(it))
    }
    y
    j
    • 3
    • 11
  • c

    Chris Fillmore

    01/07/2022, 12:05 PM
    Hello, I’d like to invite some feedback on a design I have. I am trying to model a stateful connection using a
    StateFlow<Job>
    , so that connection lifecycles can be observed, cancelled, reconnected, etc. I have an Android app which connects to several websocket endpoints on different protocols, including plain websockets, socketio, action cable, graphql subscriptions, so being able to define a common pattern like this would be useful to me. More in 🧵
    • 1
    • 6
  • t

    Trevor Stone

    01/07/2022, 7:09 PM
    I've updated to 1.6.0-native-mt and on iOS it has broken a lot of my test cases, I found https://youtrack.jetbrains.com/issue/KTOR-3612 but I am also having issues for tests that cover code that calls stateIn. I am currently doing
    .stateIn(
        CoroutineScope(Dispatchers.Default),
        SharingStarted.WhileSubscribed(),
        null
    )
    and getting
    Cannot start an undispatched coroutine in another thread DefaultDispatcher from current MainThread
    as an error from runTest
    p
    • 2
    • 17
  • r

    rkechols

    01/08/2022, 10:50 AM
    I'm trying to figure out how to best set up coroutines/flows to show updates to nested objects. Specifically, I need to display a
    Group
    object, which has some normal data to display (e.g.
    id
    ), but also has a list of
    User
    objects (which each have their own data to display) I'd of course like my database to have group data separated from the
    User
    data, since `User`s can exist without a group, with multiple groups, etc. So, each group in the db will simply list the relevant
    User
    IDs; I call this a
    ShallowGroup
    I know how to get a flow to observe a single
    User
    , or how to get a flow to observe a single
    ShallowGroup
    but I can't figure out how to get from those a flow that produces full
    Group
    objects that reflect the changes to the inner
    User
    objects. My best understanding of how it would work: 1. Get a flow of
    ShallowGroup
    objects. 2. In a
    map
    call on that flow, use the user IDs in that
    ShallowGroup
    snapshot to get a flow for each
    User
    , and: 3. use
    combine
    on the previous list of flows of
    Users
    to get a flow which produces `List<User>`/`Group` 4. ?? somehow flatten the
    Flow<Flow<Group>>
    to just a
    Flow<Group>
    ?? Note that the contents of each
    ShallowGroup
    object received determine which
    User
    objects need to be observed. Can someone point me to what the best way is to handle flows for nested objects like this?
    l
    u
    • 3
    • 2
  • i

    iamthevoid

    01/09/2022, 9:32 AM
    Can anybody explain me why do sequenced setting value in MutableStateFlow doesn’t emit until last value set? there is simplified example of what i do in my app in thread. i try to collect combined value from state flow, and emits are sequenced (lines 25, 26)
    j
    • 2
    • 12
  • n

    Norbi

    01/09/2022, 9:36 AM
    Sorry if it was already mentioned here, this is a very interesting project: https://www.reddit.com/r/Kotlin/comments/rwswao/kotlin_coroutines_stack_trace_issue/
    r
    • 2
    • 2
  • s

    Stylianos Gakis

    01/09/2022, 4:19 PM
    I want to register an observer to a lifecycleOwner and remove it when this lifecycle is no longer resumed. I am currently doing:
    lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
        launch {
            val callback = LifecycleEventObserver { _: LifecycleOwner, event: Lifecycle.Event ->
                if (event == Lifecycle.Event.ON_PAUSE) {
                    // do something on pause
                }
            }
            lifecycleOwner.lifecycle.addObserver(callback)
            try {
                awaitCancellation()
            } finally {
                lifecycleOwner.lifecycle.removeObserver(callback)
            }
        }
    }
    But this
    try/finally
    with the
    awaitCancellation()
    combination feels a bit weird. Is there a nicer way to do this in general?
    a
    n
    • 3
    • 18
  • d

    dimsuz

    01/09/2022, 7:09 PM
    I am writing a custom flow and inside it I want to non-blocking collect some other flow, process it's emissions and emit them:
    val externalFlow = flowOf(1,3,4)
    val myFlow = flow<Int> {
      coroutineScope { externalFlow.collect { this@flow.emit(it + 8) } }
      emit(1)
      emit(99)
    }
    I've used
    coroutineScope
    , but I'm worried that it won't be cancelled when
    myFlow
    collection is cancelled or interrupted. It's just that I've found internal
    flowScope
    builder in
    coroutines.core
    and it says:
    This builder is similar to coroutineScope with the only exception that it ties lifecycle of children and itself regarding the cancellation, thus being cancelled when one of the children becomes cancelled.
    Can I achieve similar effect for my case? Or using
    coroutineScope
    like I did is ok?
    j
    • 2
    • 4
  • s

    Stylianos Gakis

    01/09/2022, 9:56 PM
    I’m trying to understand when I need to use
    suspendCancellableCoroutine
    over
    suspendCoroutine
    . If I got a use case where all I need to do is something like:
    suspend fun MediaPlayer.seekToPercent(
        @FloatRange(from = 0.0, to = 1.0) percentage: Float,
    ) = suspendCoroutine<Unit> { cont ->
        val callback = MediaPlayer.OnSeekCompleteListener {
            this.setOnSeekCompleteListener(null)
            cont.resume(Unit)
        }
        setOnSeekCompleteListener(callback)
        val positionToSeekTo = (duration.toFloat() * percentage).toInt()
        seekTo(positionToSeekTo)
    }
    Is there just no reason to use
    suspendCancellableCoroutine
    ? Basically I wonder if there are any other implications regarding the cancellability of
    suspendCoroutine
    and if it behaves in any different way to
    suspendCancellableCoroutine
    , or all that they do differently is that in a
    suspendCancellableCoroutine
    we have access to more than just
    resume(value: T)
    and
    resumeWithException(exception: Throwable)
    ? Reading the documentation doesn’t fill all the gaps in my head
    d
    j
    a
    • 4
    • 17
  • e

    Eli

    01/09/2022, 10:49 PM
    Kinda similar question as above, but maybe a little simpler. I'm reading the documentation for Flows, and I'd like to implement a Flow that executes each of the items concurrently. And when I'm reading the docs, I see https://kotlinlang.org/docs/flow.html#buffering which explains quite well that this should be possible without explicitly calling
    launch
    or
    async
    on the calling function. I'm trying to implement this as close to the example as I can, but no matter what I do, it doesn't seem to be executing the items in the flow concurrently, but only sequentially. Here's a simplified code snippet of what I'm attempting:
    enum class Ordinal(val delay: Long) {
    		FIRST(100),
    		SECOND(200),
    		THIRD(300),
    		FOURTH(400),
    		FIFTH(500),
    		SIXTH(600),
    		SEVENTH(700)
    	}
    
    	private fun ordinalFlow() = flow {
    		for (ordinal in Ordinal.values()) {
    			delay(ordinal.delay)
    			emit(ordinal)
    		}
    	}
    
    	@Test
    	fun asyncBufferFlowTest() {
    		val blockTime = measureTimeMillis {
    			runBlocking {
    				val timer = measureTimeMillis {
    					ordinalFlow()
    						.buffer()
    						.collect { println("Collected: $it") }
    				}
    				println("Done in $timer")
    			}
    		}
    		println("Block time in $blockTime ms")
    	}
    e
    j
    • 3
    • 23
  • g

    Guilherme Almeida

    01/10/2022, 11:50 AM
    Testing the new
    limitedParallelism
    slicing I am not sure I fully understand how it works. Looking at the example below I am launching
    Access #1
    and a second later
    Access #2
    . Using the
    accessDispatcher
    with limited parallelism of 1 I would think the
    Access #2
    could only start after the
    Access #1
    was finished. So I expected the prints to go 1,2,3 but they go 1,3,2 instead. Could anyone point out why this is the actual behaviour? I know this can be solved with something like a Mutex, but I am trying to understand the behaviour of these new sliced dispatchers 😄
    private val mainScope = MainScope()
      private val accessDispatcher = Dispatchers.IO.limitedParallelism(1)
    
      public fun foo() {
        mainScope.launch {
          mainScope.launch(accessDispatcher + CoroutineName("Access #1")) {
            println("Step 1")
            delay(5.seconds)
            println("Step 2")
          }
          delay(1.seconds)
          mainScope.launch(accessDispatcher + CoroutineName("Access #2")) {
            println("Step 3")
          }
        }
      }
    j
    • 2
    • 4
  • f

    Florian Walther (live streaming)

    01/10/2022, 1:15 PM
    If I can't use the SystemClock in my unit tests, then what's the point of the time value in
    advanceTimeBy
    ? For example, I'm using a fake timesource so the actual advanced time doesn't matter.
    h
    • 2
    • 28
  • c

    Chris Fillmore

    01/10/2022, 2:47 PM
    Is there a way to observe and respond to
    Job
    state changes? (i.e. going from New -> Active -> Cancelled/Completed)
    j
    g
    z
    • 4
    • 34
Powered by Linen
Title
c

Chris Fillmore

01/10/2022, 2:47 PM
Is there a way to observe and respond to
Job
state changes? (i.e. going from New -> Active -> Cancelled/Completed)
j

Joffrey

01/10/2022, 2:49 PM
There is invokeOnCompletion to register a callback for when the job completes (successfully or exceptionally) or is cancelled
But I don't know anything for the
New -> Active
transition
c

Chris Fillmore

01/10/2022, 2:50 PM
Thanks for responding. My apologies, I knew that, and I should have been more specific, as I am primarily interested in New -> Active
j

Joffrey

01/10/2022, 2:52 PM
Ah ok, then sorry I don't know more. Why do you want to observe this transition btw?
c

Chris Fillmore

01/10/2022, 2:52 PM
Curious if anyone working on Coroutines could comment on whether it would be practical/desirable to have a method like
invokeOnStart
I am trying to do what I described here https://kotlinlang.slack.com/archives/C1CFAFJSK/p1641557100018200
j

Joffrey

01/10/2022, 2:56 PM
Why are you using the coroutine's
Job
API for this, though? It looks like your use case calls for a custom interface
c

Chris Fillmore

01/10/2022, 2:59 PM
Currently I do have a custom interface, and it creates a lot of boilerplate that I think could be eliminated simply by observing a Job
Job does virtually everything I need it to do, except being able to observe when it goes from New -> Started
It already contains mechanisms to observe cancellation/completion, it passes exceptions, I can check if it is still active, etc
I’m open to feedback on the idea… hence the original post, but there aren’t major drawbacks that are obvious to me
g

gildor

01/10/2022, 3:45 PM
To "observe" job you should use .join() it will suspend until job is complete
c

Chris Fillmore

01/10/2022, 3:46 PM
.join()
will also start the job
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 8:47 PM
You're trying to model a separate lifecycle without a coroutine job? That sounds like a bad design in general, regardless of whether it's technically possible. Very hacky to take something designed and built for one purpose and try to use it for something completely unrelated. Probably gonna give you maintenance issues later, won't be able to evolve with your needs, testing is gonna depend on a completely unrelated runtime, etc.
☝️ 2
c

Chris Fillmore

01/10/2022, 9:11 PM
You’re trying to model a separate lifecycle without a coroutine job?
No. To give a concrete example, I already have this implemented for Apollo subscriptions. It looks roughly like:
class ApolloSubscription(
  private val client: ApolloClient,
  private val coroutineScope: CoroutineScope,
) {
  private val _job = MutableStateFlow(subscriptionJob())
  val job = _job.asStateFlow()

  private var subscriptionCall: ApolloSubscriptionCall? = null

  init {
    job
      .onEach {
        it.invokeOnCompletion {
          subscriptionCall?.cancel()
          subscriptionCall = null
          if (/* should reconnect */) {
            _job.value = subscriptionJob()
          }
        }
      }
      .launchIn(coroutineScope)
  }

  private fun subscriptionJob() = coroutineScope.launch(start = CoroutineStart.LAZY) {
    suspendCancellableCoroutine {
      subscriptionCall = client.subscribe(...).apply {
        execute(object: ApolloSubscriptionCall.Callback {
          // Callback methods here that handle connection/websocket events,
          // and resume the continuation on completion/failure
        })
      }
    }
  }
}
So client code for such a class could look like:
val subscription = ApolloSubscription(...)
// Connect to the websocket
subscription.job.value.start()
// OR
subscription.job
  .onEach {
    it.start()
  }
  .launchIn(myClientScope)
To be clear, the
Job
is just meant to model, at a high level, whether or not there is an open connection, and its state. This seems in line with the definition for
Job
, from the docs
Conceptually, a job is a cancellable thing with a life-cycle that culminates in its completion.
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 9:18 PM
It still smells funny to me that the apollo client would expose coroutine jobs as part of its api for this purpose.
➕ 2
the 
Job
 is just meant to model
That was my point, that a coroutine job shouldn’t model anything other than a coroutine job
➕ 2
c

Chris Fillmore

01/10/2022, 9:22 PM
The Job is just work I guess? Maybe ‘model’ isn’t the right word, but there’s going to be a Job associated with my connection regardless of whether I model it this way or not.
Sorry I’m not trying to be argumentative, I am definitely interested in hearing downsides because I don’t want to paint myself into a corner. But I have a desire to be able to observe the state of a connection’s Job and e.g. cancel it, or lazily start it, if I want
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 9:28 PM
At the very minimum, i would strongly recommend creating your own
Job
type, even if that ends up just wrapping a coroutine job internally, to give yourself room to maneuver in the future.
c

Chris Fillmore

01/10/2022, 9:28 PM
Job
is not stable for inheritance, according to the docs. That’s not something I want to pursue.
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 9:29 PM
Yea, definitely don’t subclass it
I also don’t understand the separation of responsibilities here.
ApolloSubscription
is responsible for creating, cancelling, and recreating subscription calls, but not starting them. Why the asymmetry?
c

Chris Fillmore

01/10/2022, 9:31 PM
To be clear I’m not trying to wrap a Job or do anything special. The
StateFlow<Job>
just allows client code to observe an open connection as it changes state, reconnects, etc. This seems unremarkable to me. My original ask was whether I could observe a Job going from New -> Active state.
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 9:33 PM
It’s not remarkable, it’s just not what coroutine jobs were designed to model, and i don’t understand why you’re trying to shoehorn this use case into a very tightly-scoped, well-defined third-party thing instead of just making your own thing that you can give your own semantics and behavior.
➕ 2
c

Chris Fillmore

01/10/2022, 9:33 PM
By not starting them, they can be lazily started by the caller
z

Zach Klippenstein (he/him) [MOD]

01/10/2022, 9:42 PM
Maybe a better way to express my initial sentiment is that it’s generally dangerous to couple API this tightly to implementation (the fact that
ApolloSubscription
uses coroutines to manage calls, and how it does so, is an implementation detail of that class) – this is a pretty well-documented design best practice. But this whole discussion is moot anyway: If you need to observe when a coroutine job is started, i don’t think there are any hooks for that. You’ll have to do that some other way.
c

Chris Fillmore

01/10/2022, 9:57 PM
No the discussion is good… actually I only asked about whether or not I could observe Job start because I didn’t get any traction with my original post, which was soliciting feedback about the design. (Sorry I realize I misstated this before. Anyway.) I actually thought that this design decoupled the API from the implementation. I have several use cases where I want to use this pattern: Apollo, plain websockets (with Ktor), SocketIO, and Action Cable. My app uses all of these protocols and currently I have (IMO) boilerplate all over the place signalling whether or not something is in connecting or disconnecting or what have you state. The interface looks something like:
interface StatefulConnection {
  fun connect()
  fun disconnect()
  val state: StateFlow<State>
  
  sealed interface State {
    object Initializing
    object Connecting
    object Connected
    ... others ...
  }
}
I find this creates a lot of intermediate state and is a risk for bugs. What I really want to know is if the connection is still alive or if there was an error, and I want to be able to cancel the Job. Tracking the Job that’s running the socket connection does this just fine. It doesn’t feel like shoehorning at all. (I’ve done plenty of shoehorning before… this doesn’t feel like it, though I could be wrong.)
Also to be clear, tracking the Job doesn’t preclude me from exposing other events that prove themselves useful. This is just one part of (potentially) a wider interface.
I’ll admit I took some inspiration from Ktor, which has signatures for websockets like:
// Working from memory here...
suspend fun HttpClient.wss(request: HttpRequest, block: suspend CoroutineScope.() -> Unit)
The entire lifetime of your socket connection is contained in the
block
, which I found I liked.
In my case I’ve just made it so that implementations call
launch { /* entire lifetime of your connection is contained here */ }
View count: 10