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

    Florian

    01/30/2021, 10:46 AM
    Would it be possible to rewrite this in a way that
    Loading
    keeps emitting database updates rather than only a single result (
    first
    )?
    flow {
        val data = query().first()
    
        val flow = if (shouldFetch(data)) {
            emit(Resource.Loading(data))
    
            try {
                saveFetchResult(fetch())
                onFetchSuccess()
                query().map { Resource.Success(it) }
            } catch (t: Throwable) {
                onFetchFailed(t)
                query().map { Resource.Error(t, it) }
            }
        } else {
            query().map { Resource.Success(it) }
        }
        emitAll(flow)
    }
    d
    • 2
    • 6
  • v

    Vikas Singh

    01/30/2021, 1:27 PM
    how can we know that our suspendcancellable coroutine is cancelled ?
    z
    m
    • 3
    • 2
  • g

    Gilles Barbier

    01/30/2021, 6:04 PM
    Hi, I'm writing a client that needs to transform an asynchronous execution to a synchronous one: when receiving a request, the client sends a message to a queuing system and waits for a response in a response queue (one per client instance). When receiving the response, it should return it to the initial synchronous request. Note that multiple requests can be done in parallel on the same client instance. I'm not sure how to implement that. Any suggestion ? Is there a coroutine pattern associated to this situation? Thanks
    g
    • 2
    • 2
  • f

    Florian

    01/31/2021, 2:22 PM
    is it possible to call
    emitAll
    inside a Flow, execute some other operation in parallel, and then switch to a different
    emitAll
    once the operation is done?
    d
    • 2
    • 3
  • d

    Dominaezzz

    01/31/2021, 5:03 PM
    Is there a better (more correct?) way to write this operator?
    @ExperimentalCoroutinesApi
    internal fun <T> Flow<T?>.coalesce(other: Flow<T>): Flow<T> {
        return distinctUntilChanged { old, new -> old == null && new == null }
            .transformLatest {
                if (it != null) {
                    // TODO: Will "Latest" wrongly cancel this branch?
                    emit(it)
                } else {
                    emitAll(other)
                }
            }
    }
    e
    • 2
    • 1
  • c

    christophsturm

    01/31/2021, 6:22 PM
    is there a way to write this code:
    class Worker(val id: Int) {
        fun work(): Worker {
            Thread.sleep(1000)
            return Worker(id)
        }
    }
    
    
    println(measureTimeMillis { runBlocking {
        listOf(Worker(1), Worker(2), Worker(3))
            .map { worker ->
                async(Dispatchers.Default) {
                    val worker2 = worker.work()
                    worker2.work()
                }
            }.awaitAll()
    }})
    with 2 maps instead?
    listOf(Worker(1), Worker(2), Worker(3)).map {it.work()}.map{it.work()}
    but still running the workers in multiple threads? I know how i could do it with a channel, but is it also possible with a flow?
    a
    • 2
    • 3
  • v

    Vivek Sharma

    01/31/2021, 6:47 PM
    Can we create flow in different dispatcher and collect flow in the different dispatcher, I was playing around while learning flow and wrote a code, Can someone explain
    g
    • 2
    • 10
  • a

    Aditya Wasan

    02/01/2021, 6:05 AM
    Hey guys, I have a question regarding MutableStateFlow. I have a MutableStateFlow in my repo which is being observed in the ViewModel. However, the ViewModel is not receiving any updates. Here's the StateFlow that I have in my repository
    private val _isCacheReady = MutableStateFlow(false)
    val isCacheReady = _isCacheReady.asStateFlow()
    After filling up the cache, I'm updating the value
    _isCacheReady.value = true
    And here's the observing code
    init {
      lobstersRepository.isCacheReady.onEach {
        _savedPosts.value = lobstersRepository.getAllPostsFromCache()
      }.launchIn(viewModelScope)
    }
    d
    z
    • 3
    • 11
  • f

    Florian

    02/01/2021, 9:13 AM
    Can anyone sanity check this
    channelFlow
    ? It seems to work as intended, I just want to make sure I'm not doing anything dumb. The point here is to have Loading inside the launch block emit updates while the
    try
    block is running concurrently. I think I don't need to call
    awaitClose
    because collection from the query never ends.
    inline fun <ResultType, RequestType> networkBoundResource(
        crossinline query: () -> Flow<ResultType>,
        crossinline fetch: suspend () -> RequestType,
        crossinline saveFetchResult: suspend (RequestType) -> Unit,
        crossinline onFetchSuccess: () -> Unit = { },
        crossinline onFetchFailed: (Throwable) -> Unit = { },
        crossinline shouldFetch: (ResultType) -> Boolean = { true }
    ) = channelFlow {
        val data = query().first()
    
        if (shouldFetch(data)) {
            val loading = launch {
                query().collect { send(Resource.Loading(it)) }
            }
    
            try {
                saveFetchResult(fetch())
                onFetchSuccess()
                loading.cancel()
                query().collect { send(Resource.Success(it)) }
            } catch (t: Throwable) {
                onFetchFailed(t)
                loading.cancel()
                query().collect { send(Resource.Error(t, it)) }
            }
        } else {
            query().collect { send(Resource.Success(it)) }
        }
    }
    k
    • 2
    • 4
  • p

    Pablo

    02/01/2021, 9:43 AM
    Hello guys is there any explanation for
    suspend fun
    for dummies? I mean, if you would have to explain what is a
    suspend
    for someone that is completely new on this world of coroutines what would be your answer?
    l
    n
    v
    • 4
    • 33
  • c

    Christian Ekrem

    02/01/2021, 1:16 PM
    Hey! I need some help understanding something. Somewhere in my code there’s a method for fetching Something. The method should return a flow that initially emits the cached value, and then emits the “fresh” value after querying our API. Most of this is done by Room – Room emits new data whenever a given table is updated. I’ve got it working, but I tried making the code a bit simpler and that’s where both the functionality and my understanding broke 😞
    // stream is _really_ someDao.loadAll(): Flow<Something>
    val stream = MutableStateFlow("cachedValue")
    
    // refresh is _really_ fetchSomethingFromApi.also { someDao.updateData(it) }
    val refresh = suspend {
        delay(1000)
        stream.value = "freshValueFromAPI"
    }
    
    suspend fun whyDoesThisNotWork(): Flow<String> = stream
        .onStart {
            coroutineScope {
                launch {
                    refresh()
                }
            }
        }
    
    suspend fun thisWorks(): Flow<String> = flow {
        coroutineScope {
            launch {
                refresh()
            }
    
            stream.collect {
                emit(it)
            }
        }
    }
    It’s not like the working version is horrible, I just want to understand why the first one does not work!
    • 1
    • 2
  • p

    Pablo

    02/01/2021, 2:35 PM
    How do you know wether you use Dispatchers.Default on Android side? In terms of mapping objects? If it's a 1:1 mapper is it really needed to use withContext(Dispatchers.Default)? I thought that it's needed when you need to do heavy operations like sorting, etc..?
    m
    • 2
    • 8
  • b

    Brais Gabin

    02/01/2021, 7:57 PM
    Is there any way to get a Sharable Flow that ends? I have a slow producer with an end. And I have multiple slow consumers that need all the produced items. My current solution is convert that Flow in a List and then start the consumers. But I'm losing time because some consumers can start it's work as soon as the producer emits the first element.
    m
    • 2
    • 1
  • g

    Guillermo Alcantara

    02/02/2021, 12:58 AM
    Anyone knows why a mutableSharedFlow.collect might not be called during a Unit Test?
    @Test
        fun testFoo() = runBlocking {
            val testCoroutineScope = TestCoroutineScope().apply {
                pauseDispatcher() // This needs to be here because the actual test, handles time.
            }
            val sharedFlow = MutableSharedFlow<Int>()
            val values = mutableListOf<Int>()
            println("before launch")
            val job = testCoroutineScope.launch {
                println("before collect")
                sharedFlow.collect {
                    println("before adding $it")
                    values.add(it)
                }
            }
    
            println("before emits")
            sharedFlow.emit(1)
            sharedFlow.emit(2)
            testCoroutineScope.runCurrent()
    
            assertEquals(mutableListOf(1, 2), values)
    
            job.cancel()
        }
    f
    t
    • 3
    • 22
  • p

    Pablo

    02/02/2021, 9:40 AM
    Is this any reason to use
    return suspendCoroutine{
       continuation -> usecase.invoke{result -> continuation.resumeWith(Result.success(result)}
    }
    Is there any difference between suspendCancellableCoroutine? Becuase I know I've been using this for instance for firebase sign in
    g
    a
    • 3
    • 9
  • a

    albertosh

    02/02/2021, 1:29 PM
    Hi everyone! Some time ago,
    Flow.onEmpty
    operator was added (https://github.com/Kotlin/kotlinx.coroutines/issues/1890) Is there any plan for including
    Flow.onNotEmpty
    ? Use case is a method that return paginated data and you need all the items
    fun getData(page: Int, pageSize: Int): Flow<Item> = ...
    fun getAllData() = getAllData(0, 5)
    
    private fun getAllData(page: Int, pageSize: Int): Flow<Item> = flow {
      val data = getData(page, pageSize)
      emitAll(data)
      data.onNotEmpty { emitAll(getAllData(page + 1, pageSize) }
    }
    Maybe I’m not following a proper approach, some other ideas I had using count
    private fun getAllData(page: Int, pageSize: Int): Flow<Item> = flow {
      val data = getData(page, pageSize)
      emitAll(data)
      if (data.count() == pageSize) {         // Since `count` does a `collect`, another flow is created
        emitAll(getAllData(page + 1, pageSize) 
      }
    }
    To avoid creating two flows per page, I tried with a
    SharedFlow
    but since it never ends you can’t invoke count BTW, I’m intending to use it on backend side, so not sure if I can use the Paging Library from Jetpack
    d
    • 2
    • 1
  • v

    Vivek Sharma

    02/02/2021, 5:33 PM
    so when I use StateFlow, the consumer dont unregister when view is in STOPPED state, then this will consume more resources or something then why should we use stateflow instead of livedata? I cant understand the use of stateflow and below is snippet written in docs
    Untitled
    j
    o
    j
    • 4
    • 15
  • v

    voben

    02/02/2021, 5:41 PM
    I want to test if a certain event was emitted to my shared flow, but that event gets emitted in the init function before I can observe the flow in my test. How do I test that this event was actually emitted?
    @Test
        fun `test event is emitted`() = coroutineRule.runBlockingTest {
    
           val viewModel = MyViewModel()
           launch {
                val elements = viewModel.mySharedFlow.take(1).toList()
                elements[0] shouldBeEqualTo MyEvent
            }
        }
    // ViewModel
    val mySharedFlow = MutableSharedFlow<MyEvent>(extraBufferCapacity = 1)
    
     init {
        mySharedFlow.tryEmit(MyEvent)
     }
    z
    d
    m
    • 4
    • 6
  • b

    Ben Butterworth

    02/02/2021, 6:15 PM
    Should functions (e.g. in ViewModel or even Service) select the context (
    withContext(context)
    or
    async(context) {}
    )
    and return
    Deferred
    , or should callers have the responsibility to select the context? I would think its cleaner to encapsulate the context choice to a lower level function itself. Fragment/Activity calls ViewModel calls Service calls API. The Service returns a
    Result<T>
    , and I originally made ViewModel functions return
    Deferred<T>
    , so Fragments need to
    await
    it. However, I found lots of examples calling
    async {}
    everywhere the functions are called, so callers need to know which context to use, which they will likely know less than the API designer. Also, the
    withContext
    coroutine function seems to imply people should be calling it in fragments/ highest level. I assume this because
    withContext
    seems ‘terminal’ (it suspends until it completes). I am still working on my coroutine understanding, so I would appreciate any help 🙂
    d
    u
    • 3
    • 7
  • t

    taer

    02/02/2021, 10:12 PM
    Slightly different question from yesterday. I have a flow that can only be consumed once(a grpc stream). I need to pull the first element off like with
    first
    but I don't want to close the flow. I need the rest of the elements to be still available.
    t
    • 2
    • 7
  • s

    Simon Lin

    02/03/2021, 3:14 AM
    Do I need to check
    SendChannel::isClosedForSend
    every time when I send? If the channel could be close in any time.
    t
    • 2
    • 1
  • z

    zjuhasz

    02/03/2021, 8:17 AM
    Is there a way to check if a
    SharedFlow
    that is set to
    BufferOverflow.DROP_OLDEST
    actually drops a value from its buffer due to the buffer being full? I would like to log a warning when this occurs.
    t
    • 2
    • 2
  • m

    Mikael Alfredsson

    02/04/2021, 1:03 PM
    is there a way to perform “awaitAny” on a collection of jobs? i.e wait for first that finishes?
    l
    o
    • 3
    • 34
  • s

    Stephen Edwards

    02/04/2021, 3:40 PM
    Does anyone know why GlobalScope Dispatchers.Default contexted coroutines were implemented using Daemon Threads?
    ➕ 1
    n
    z
    • 3
    • 5
  • a

    Afzal Najam

    02/04/2021, 5:03 PM
    So I just tried this in a Kotlin/JVM project, and it didn't work as I thought it would. If I create a scope like this, and one of its children jobs had an exception, the parent cancels and no other coroutines can be launched:
    val parentScope = CoroutineScope(Dispatchers.Default + Job() + exceptionHandler)
    But if I create it like this, and one of its children jobs had an exception, siblings didn't fail and other coroutines were able to launch just fine:
    val parentScope = MyScope()
    Where
    MyScope
    is:
    class MyScope: CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = Dispatchers.Default + Job() + exceptionHandler
    }
    I thought that both `parentScope`s would behave exactly the same. Am I missing something? Here's a gist: https://gist.github.com/AfzalivE/3bfe168e879ba8b97ad62292217b0491
    l
    i
    • 3
    • 16
  • t

    Tristan Hamilton

    02/04/2021, 10:18 PM
    I was messing around with launching coroutines inside an async parent coroutine and the effects on their completion when cancelling that parent scope. I wanted to see could they still be cancelled early if passed as a lambda to a function that would wrap them in a parent coroutine. Doesn't seem to work as I expected. Here's a gist - https://gist.github.com/Munzey/212f38879039987a4c819c53d1d393cd maybe its just something one should never do, but maybe someone can explain to me why it doesn't work the way I thought it would 🙂 cheers!
    m
    • 2
    • 11
  • w

    wasyl

    02/05/2021, 7:39 AM
    I encountered an unexpected (for me) behaviour with coroutines and I’m not quite sure if I should report it. Basically sometimes Kotlin generates code that holds onto some variables even if I null them out in another coroutine. That was unexpected for me, as I was writing the following test:
    inCoroutine {
        var foo: Foo? = Foo()
        val fooRef = WeakReference(foo)
    
        triggerAndWaitForGc()
        assert(fooRef.get() != null)
    
        println(foo) // Test passes if this is removed
    
        inCoroutine {
            foo = null
            triggerAndWaitForGc()
            assert(fooRef.get() == null)
        }
    }
    So first I hold
    Foo
    in a strong reference (variable) and assert
    WeakRef
    also has a reference to it. But later I set
    foo = null
    , at which point I expect that there’s no strong reference to
    Foo
    and it can be GC-ed. This doesn’t happen in the snippet above, because
    println(foo)
    generates the following bit:
    Foo var9 = (Foo)foo.element;
    var5 = false;
    System.out.println(var9);
    and
    var9
    is never cleared, so there will be a strong reference to
    Foo
    as long as that coroutine is active (?). Is this expected? Snippet with full code: https://pl.kotl.in/25D0_X5w8
    t
    • 2
    • 13
  • a

    allan.conda

    02/05/2021, 8:42 AM
    Any idea how I can improve this? I don’t need the first two vals, but I want to trigger the call at the same time
    Untitled.kt
    j
    • 2
    • 5
  • n

    Nikola Milovic

    02/05/2021, 12:41 PM
    Hey everyone, looking at the docs for CoroutineWorker from WorkManager, I came across this
    class CoroutineDownloadWorker(
        context: Context,
        params: WorkerParameters
    ) : CoroutineWorker(context, params) {
    
        override suspend fun doWork(): Result {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                val data = downloadSynchronously("<https://www.google.com>")
                saveData(data)
                return Result.success()
            }
        }
    }
    Which wouldn't work? As it has to be
    return@withContext
    and you need a return value outside of it? Or I am I missing something
    m
    • 2
    • 3
  • f

    Florian

    02/05/2021, 12:55 PM
    What actually cancels a Flow? The act of stopping to collect it?
    m
    • 2
    • 6
Powered by Linen
Title
f

Florian

02/05/2021, 12:55 PM
What actually cancels a Flow? The act of stopping to collect it?
m

Marc Knaup

02/05/2021, 12:59 PM
afaik a Flow ends if either • the Flow is complete (no more elements, or exception thrown - e.g. when canceled). • the Flow collector has thrown an exception - e.g. when cancelled.
takeWhile
and alike throw a
CancellationException
internally
f

Florian

02/05/2021, 1:03 PM
thank you
so when I collect in a coroutine scope and that scope is cancelled, the Flow is definitely cancelled
m

Marc Knaup

02/05/2021, 1:26 PM
Yes, same with
launchIn(scope)
f

Florian

02/05/2021, 1:28 PM
thank you
View count: 5