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

    03/23/2021, 8:57 PM
    I'm confused as how to to plug a suspending function into a flow I notice the flowOf builder, but that requires value, so that means its evaluated beforehand I'd expect something like this
    flowOf {
       someSuspendFunction()
    }
    am I missing something, or is it left to clients to create such extension comming from rx, I have it mapped in by brain as such
    Observable.just == flowOf(value)
    Observable.fromCallable == flowOf { .. }
    e
    a
    +2
    • 5
    • 19
  • v

    vineethraj49

    03/24/2021, 12:24 PM
    if all my
    Dispatchers.Default
    threads (
    Runtime.getRuntime().availableProcessors()
    ) are blocked under
    runBlocking
    , a
    GlobalScope.future(<http://Dispatcher.IO|Dispatcher.IO>)
    also fails to launch; why is this the case?
    c
    u
    • 3
    • 3
  • u

    ursus

    03/24/2021, 2:06 PM
    So.. is it safe to use
    runCatching
    in coroutines for control flow? I gather it will catch CancelationException as well. Won't that break stuff?
    👍 1
    e
    d
    o
    • 4
    • 5
  • b

    Brian Dilley

    03/24/2021, 4:06 PM
    I updated my question and posted it to stack overflow: https://stackoverflow.com/questions/66784930/how-to-find-first-desired-result-from-kotlin-coroutines-deferred-server
    n
    u
    • 3
    • 5
  • n

    natario1

    03/25/2021, 3:55 PM
    Is this a known issue? https://pl.kotl.in/ILirg4-hM Using Result as flow type throws ClassCastException.
    l
    • 2
    • 2
  • p

    Patrick Ramsey

    03/26/2021, 12:39 AM
    I’m having trouble wrapping my head around a paragraph in the Coroutines Basics doc:
    But what if the extracted function contains a coroutine builder which is invoked on the current scope? In this case, the
    suspend
    modifier on the extracted function is not enough. Making
    doWorld
    an extension method on
    CoroutineScope
    is one of the solutions, but it may not always be applicable as it does not make the API clearer. The idiomatic solution is to have either an explicit
    CoroutineScope
    as a field in a class containing the target function or an implicit one when the outer class implements
    CoroutineScope
    . As a last resort, CoroutineScope(coroutineContext) can be used, but such an approach is structurally unsafe because you no longer have control on the scope of execution of this method. Only private APIs can use this builder.
    Particularly, what does it mean that having an explicit CoroutineScope as a field on a class containing the target function is preferable to calling CoroutineScope(…)? How else would you create an explicit CoroutineScope as a field, other than
    val scope = CoroutineScope(…)
    ?
    z
    • 2
    • 31
  • a

    Antoine Gagnon

    03/26/2021, 5:26 PM
    Hey everyone, I’m having some issues finding some way to do something similar to DispatchQueue in Swift What I want to do is launch one coroutine off the main thread with the first queue element and when it’s done, launch the next in queue. I could implement something with async and all that, but I was wondering if there’s anything that already exists to support this behaviour?
    z
    b
    • 3
    • 10
  • e

    Emil Kantis

    03/26/2021, 6:57 PM
    Hi! Does anyone know how I should be able to compare a return value with
    COROUTINE_SUSPENDED
    ? I'm building an AOP-based logging interceptor and need to check if the return value of a reflective methodcall is
    COROUTINE_SUSPENDED
    🙂 Currently doing this by checking
    if (result.toString() == "COROUTINE_SUSPENDED")
    but it feels like I should be able to access the symbol directly..
    l
    • 2
    • 2
  • z

    zak.taccardi

    03/27/2021, 6:48 PM
    it still seems unclear whether to use
    callbackFlow
    vs
    channelFlow
    . It seems the latter respects operator fusion, but the prior does not?
    d
    u
    s
    • 4
    • 9
  • u

    ursus

    03/28/2021, 2:14 PM
    If I were to inject CoroutineScope everywhere, do you bother to make sure nobody calls cancel on you? Is there some base interface so I dont need to compose myself?
    s
    • 2
    • 2
  • b

    Byron Katz

    03/28/2021, 9:19 PM
    I've been holding off from coroutines a while now. Every time I tried adding them, I'd run into severe headwinds. Today I tried again, and basically just converted my executor service like this:
    -    executorService: ExecutorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory())
    +    executorService: ExecutorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory()).asCoroutineDispatcher().executor as ExecutorService,
    and bam! Performance up by 40% on my heaviest function.
    e
    • 2
    • 13
  • l

    Lilly

    03/28/2021, 9:28 PM
    Hi, I have a
    coroutineScope
    and within this scope I want to cancel it. How can I prevent cancel cooperation of this scope, so that cancellation isn't propagated?
    n
    • 2
    • 2
  • s

    svenjacobs

    03/29/2021, 6:32 AM
    Hi all, I have a weird behaviour regarding coroutines on Android and I hope that you can help me: I have a suspending function that performs some UI logic
    suspend fun showSnackbar() {
        val snackbar = Snackbar.make(...)
        snackbar.show()
        delay(4000)
        snackbar.setAction("...", null) // crash here
        snackbar.dismiss()
    }
    The functions is called via
    launch(Dispatchers.Main) { showSnackbar() }
    . Please don't ask why I have to
    null
    the action. It is required to prevent a false positive memory leak warning. Anyway, the call
    snackbar.setAction()
    crashes the app with
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    and I wonder if
    delay()
    might change the Dispatcher?? 🤔 Thanks for your help!
    u
    l
    • 3
    • 27
  • l

    Lilly

    03/29/2021, 8:58 AM
    Can someone explain me why the second child is not cancelled?
    coroutineScope {
    		launch {
    			if (condition) cancel() // does not cancel the coroutine of flow
    		}
    		
    		launch {
    			dataSource.channel.receiveAsFlow() {
    				.collect { doSomething() }
    		}
    	}
    I would expect that cancelling first coroutine would cancel second coroutine but it doesn't. Any ideas?
    l
    a
    • 3
    • 7
  • l

    Lukasz Kalnik

    03/29/2021, 3:29 PM
    Is there an operator for
    SharedFlow
    that cancels the flow automatically after all subscribers have left? Something like
    refCount()
    in RxJava.
    b
    e
    u
    • 4
    • 13
  • l

    Lilly

    03/29/2021, 3:51 PM
    Is it possible to receive from a
    Channel
    without removing the element?
    z
    i
    • 3
    • 3
  • u

    ursus

    03/29/2021, 9:50 PM
    why is this
    fun intervalFlow(delayMillis: Long): Flow<Int> {
        return flow {
            withContext(Dispatchers.Default) {
                var i = 0
                emit(i)
                while (true) {
                    delay(delayMillis)
                    emit(++i)
                }
            }
        }
    }
    wrong -- I mean I read the article, but at runtime it doesnt crash, and printing threads in each step, seems correct
    l
    • 2
    • 1
  • d

    dewildte

    03/29/2021, 11:15 PM
    Ok so I think the answer to this is yes but is it unsafe to have a
    ViewModel
    collect from a
    Flow<T>
    given to it by a
    View
    ,
    Activity
    or
    Fragment
    ? I.E.
    // MyView.kt
    val events: Flow<Event> = flowOf(Event1, Event2)
    
    viewModel.handleEvents(events)
    a
    u
    h
    • 4
    • 19
  • u

    ursus

    03/30/2021, 2:35 AM
    Is there a testing library other than turbine, which would work with MutableStateFlow, i.e. sideffecting type of code? (toList hangs) in rx it would looks like this
    @Test fun `doSomething should move state to FINAL`() {
        val viewModel = createViewModel(initialState = State.INITIAL)
    
        val testSubscriber = viewModel.state.test()
        viewModel.doSomething()
    
        testSubscriber.assertValues(State.INITIAL, State.FINAL)
    }
    g
    j
    e
    • 4
    • 6
  • t

    TheMrCodes

    03/30/2021, 10:12 AM
    I know this is a recurrent question and Im a bit sorry for asking again but: Q: What is currently the best an simplest way to ensure that a mutable variable is only changed by one coroutine simultaneously? A:
    MutableStateFlow
    ✅ 1
    t
    h
    +2
    • 5
    • 11
  • s

    Susheel

    03/30/2021, 6:15 PM
    If I run into an NPE on that line, how would I fix it?
    c
    • 2
    • 5
  • o

    Oleg Siboglov

    03/30/2021, 11:19 PM
    Hey everybody. I was hoping I could get some help in how to best approach this situation… I have a suspending function that returns some data. I may need to suspend the coroutine that called the function while something else is done asynchronously, and then resume the coroutine, eventually returning data from that function.
    suspend fun foo(): Bar {
        // I call another suspend function here returning an intermediate value.
        if (error) {
            suspendCancellableCoroutine<Bar> { continuation ->
                val listener = object : Listener {
                    override fun callback() {
                        // I need to call this suspend function again.
                        // However, here is where I get an error.
                        continuation.resume(foo())
                    }
                }
                // I call other functions that will eventually call the listener.
            }
        }
    }
    The error that I get is obvious -
    Suspension functions can be called only within coroutine body
    . However, I’m not really quite sure on how to resume the coroutine properly. Any help is much appreciated. Thank you.
    e
    c
    u
    • 4
    • 3
  • d

    dan.the.man

    03/31/2021, 4:38 PM
    Does anyone know of any good articles on replacing RxRelay with Stateflow/SharedFlows?
    d
    p
    • 3
    • 2
  • n

    Noel Stieglitz

    03/31/2021, 7:28 PM
    Hi Everyone! I have a question that straddles the Android/coroutine slack channels, but I think the heart of the question is about structured concurrency. I'm working on an Android app that has a ViewModel that references a repository. The repository exposes a method that makes two concurrent API calls and returns the result of both after both have finished. What I have now is something like this:
    suspend fun fetchTwoThings(): TheResultsModel =
                coroutineScope {
                    val job1 = getStuff1(this) // both of these functions use the passed in coroutine scope like scope.async(<http://Dispatchers.IO|Dispatchers.IO>) { ... API call here }
                    val job2 = getStuff2(this)
                    awaitAll(job1, job2)
    
                    return@coroutineScope TheResultsModel(
                            thing1 = job1.await(),
                            thing2 = job2.await()
                }
    Is there any downside to using the
    coroutineScope
    like this in the repository? Alternatively, I could pass in the
    viewModelScope
    . Maybe that's ok since the ViewModel class instantiates the repo as a member variable. The lifetime of the repository is already tied to the ViewModel class. Yet another option is to expose
    getStuff1
    and
    getStuff2
    to the ViewModel, and manage the coroutine there. I'm not a huge fan of that since I might want to call
    fetchTwoOtherThings
    from other places and would have to duplicate that code. What are your thoughts? How can I do this better?
    z
    u
    • 3
    • 7
  • u

    ursus

    03/31/2021, 8:47 PM
    Is
    Dispatchers.Unconfined
    equal to rx
    Schedulers.trampoline()
    ? if so, why does my code not run blockingly if I replace all dispatcher references with the
    Unconfined
    one? That's what I used to do for testing in rx Is it not supposed to? To not impose any threading, i.e. run on native unit test thread? (Im aware of TestDispatcher, that works as expected)
    e
    • 2
    • 1
  • a

    alex.tavella

    03/31/2021, 9:10 PM
    Has anybody had ever written timeout tests for Retrofit with MockWebServer + coroutines? I’m getting
    This job has not completed yet
    on the following test:
    @Test
        fun requestWithTimeout_serverRespondsInTime_returnsResponse() = coroutinesRule.testDispatcher.runBlockingTest {
            val body = "{ field: Test }"
            val response = MockResponse()
                .setResponseCode(HttpURLConnection.HTTP_OK)
                .setBody(body)
                .throttleBody(body.length.toLong() / 2, 9, TimeUnit.SECONDS)
    
            mockWebServer.enqueue(response)
    
            val actual = service.requestWithTimeout(20_000)
    
            assertEquals(ResponseTest("Test"), actual)
        }
    👍 1
    j
    u
    • 3
    • 17
  • s

    Shawn Witte

    03/31/2021, 9:25 PM
    I have a remote call (
    suspend
    function via Retrofit) that is part of my (Android app's ) data syncing. I am attempting to ensure that the code block with this call completes, even if the calling coroutine (started in a
    viewModelScope
    ) is cancelled. My initial thought was to wrap the function in
    appScope.async { //code }.await()
    , where
    appScope
    is an application-level scope. Android Studio has suggested that I just use
    withContext(appScope.coroutineContext) { //code }
    . Are these really equivalent in terms of coroutine lifecycles? I had thought that
    withContext
    created a child coroutine (with a different, but related
    CoroutineContext
    ) that would be cancelled if the context creating it is cancelled, whereas
    appScope.async()
    creates a whole new coroutine with its own lifecycle tied to
    appScope
    and not the original context. Also welcoming input on my solution to the initial problem.
    ➕ 1
    u
    n
    s
    • 4
    • 8
  • d

    Dmytro Serdiuk

    04/01/2021, 4:10 PM
    Hello! I’m new to Kotlin and checking the documentation, I found some statement for this code:
    fun main() = runBlocking<Unit> {
        val counter = counterActor() // create the actor withContext(Dispatchers.Default) {
            massiveRun { 
                counter.send(IncCounter)
            } 
    }
        // send a message to get a counter value from an actor
        val response = CompletableDeferred<Int>() 
        counter.send(GetCounter(response)) 
        println("Counter = ${response.await()}")     
        counter.close() // shutdown the actor
    }
    Actor is more efficient than locking under load, because in this case it always has work to do and it does not have to switch to a different context at all. How to understand it?And how is it efficient than locks?
    g
    • 2
    • 15
  • d

    dan.the.man

    04/01/2021, 4:54 PM
    If I have a Stateflow is there a difference between
    emit(newValue)
    and
    value = newValue
    like there was for post/value in Livedata? I'm not seeing any documentation, I think we're supposed to use Emit, but using value = appears to be working in my code?
    z
    o
    • 3
    • 6
  • r

    Robert Jaros

    04/01/2021, 10:48 PM
    Would it be somehow possible to "intercept" StateFlow subscriptions (and do something before and after all subscribers get new value)?
    e
    d
    • 3
    • 3
Powered by Linen
Title
r

Robert Jaros

04/01/2021, 10:48 PM
Would it be somehow possible to "intercept" StateFlow subscriptions (and do something before and after all subscribers get new value)?
e

ephemient

04/01/2021, 11:15 PM
.onEach {}
would be "before" subscribers get each value, although the resulting type isn't StateFlow anymore so not sure if that would work for you
and it's unclear to me what "after" should mean, you can't control when a subscriber is "done" handing a value
d

Dominaezzz

04/02/2021, 5:53 AM
Transform
View count: 6