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

    ursus

    10/24/2020, 9:35 PM
    I used the replaying behavior in rx to cache the latest emit of database, and scope in rx is .. I guess the duration of FooRepository instance lifetime (foo flow instance lifetime)? Well..semantically its not GlobalScope since FooRepository say only lives during user being logged in -- dagger specifies this If I were to have scope as param that would not be nice api. Or maybe use GlobalScope and just leave it up to dagger to scope the FooRepository object, and therefore GC eats this when it goes out of "scope"? Would that be a leak?
    g
    15 replies · 2 participants
  • u

    ursus

    10/24/2020, 9:41 PM
    -- also, why is a scope needed if say one wants a
    refCount
    behavior? I dont see how is it relevant
    g
    1 reply · 2 participants
  • w

    william

    10/25/2020, 6:28 PM
    my flow is
    Flow<List<T>>
    , can i convert it to
    Flow<T>
    with something like
    flatten
    on arrays on std lib?
    b
    l
    +1
    10 replies · 4 participants
  • n

    nwh

    10/25/2020, 6:58 PM
    Is it possible to ensure that a channel only ever receives a single value? For example, setting the capacity to 1, and immediately closing it such that any call to
    offer
    will throw an exception. I'm worried about the synchronization between the close call and the offer call. ie I need an atomic receiveAndClose (though I don't need it to be a channel)
    a
    t
    4 replies · 3 participants
  • f

    Florian

    10/26/2020, 12:29 AM
    When you show the exception from a
    catch
    block in the UI, how do you avoid showing CancellationExceptions? Do you have to add an if check?
    z
    g
    2 replies · 3 participants
  • h

    hooliooo

    10/26/2020, 3:21 PM
    Hello, I’m currently trying to determine if my async calls are running concurrently or sequentially. I currently have this code:
    val (firstImageBlobName, firstImageThumbnailBlobName, secondImageBlobName, secondImageThumbnailBlobName) = try {
        coroutineScope {
            AsyncImageUploads(
                firstImageBlobName = async {
                    fileServiceInterface.uploadImage(
                        ...
                    )
                },
                firstImageThumbnailBlobName = async {
                    fileServiceInterface.uploadImage(
                        ...
                    )
                },
                secondImageBlobName = async {
                    fileServiceInterface.uploadImage(
                        ...
                    )
                },
                secondImageThumbnailBlobName = async {
                    fileServiceInterface.uploadImage(
                        ...
                    )
                }
            )
        }
    } catch (e: Exception) {
        ....
    }
    
    repository.save(
        model.copy(
            firstImage = firstImageRepository.save(
                FirstImage(
                    imageURL = firstImageBlobName.await(),
                    thumbnailURL = firstImageThumbnailBlobName.await(),
                    model = model
                )
            ),
            secondImage = secondImageRepository.save(
                SecondImage(
                    imageUrl = secondImageBlobName.await(),
                    thumbnailUrl = secondImageThumbnailBlobName.await(),
                    model = model
                )
            )
        )
    )
    The issue is the upload takes around 40 seconds to finish 🤔 so I’m wondering if the async calls are happening concurrently
    l
    m
    +1
    9 replies · 4 participants
  • v

    vitaliy

    10/26/2020, 5:26 PM
    Hi everybody, I’m having an issue with
    BroadcastChannel
    and
    Flow
    . Essentially I’m looking for the
    navigate
    to behave like rx
    PublishSubject
    . Issue: since
    navigate
    flow is created from the channel,
    firstOrNull()
    on it never finishes. I’m pretty new to coroutines and I will appreciate if somebody can have a look. Thanks!
    import io.kotest.matchers.shouldBe
    import kotlinx.coroutines.channels.BroadcastChannel
    import kotlinx.coroutines.channels.Channel
    import kotlinx.coroutines.flow.asFlow
    import kotlinx.coroutines.flow.firstOrNull
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.runBlocking
    import org.junit.jupiter.api.Test
    
    class RetainStateTest {
    
        val navigateChannel = BroadcastChannel<List<String>>(Channel.BUFFERED)
        val navigate = navigateChannel.asFlow()
    
        val data = listOf("blah", "foo")
    
        @Test
        fun `should not retain state`() {
            runBlocking {
                val jobPrecondition = launch {
                    navigate.firstOrNull() shouldBe data
                }
                navigateChannel.send(data)
                jobPrecondition.join()
    
                val job = launch {
                    navigate.firstOrNull() shouldBe null
                }
                job.join()
            }
        }
    }
    z
    b
    12 replies · 3 participants
  • v

    Vsevolod Tolstopyatov [JB]

    10/26/2020, 6:54 PM
    📣 📣 📣 kotlinx.coroutines 1.4.0 is here! •
    StateFlow
    and
    SharedFlow
    are promoted to stable API • Rewritten and fully optimized `Flow.combine`: better performance and no more SIGSEGV on Mediatek devices • Various improvements and bug fixes Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.4.0
    ❤️ 18
    🎉 46
    😒uspend: 6
    t
    z
    +4
    9 replies · 7 participants
  • y

    Yuri

    10/26/2020, 8:42 PM
    @Vsevolod Tolstopyatov [JB] Could you please clarify if
    SendChannel.offer should never throw
    was fixed in 1.4.0 release? https://github.com/Kotlin/kotlinx.coroutines/issues/974
    ➕ 3
    e
    1 reply · 2 participants
  • y

    Yuri

    10/26/2020, 8:43 PM
    Also, do we need separate
    -native-mt
    library for 1.4.0 release for multi-threaded coroutines on KMM?
    b
    v
    +3
    10 replies · 6 participants
  • o

    Orhan Tozan

    10/26/2020, 10:27 PM
    What does
    mutableSharedFlow.asSharedFlow()
    bring over
    mutableSharedFlow as SharedFlow
    ?
    e
    1 reply · 2 participants
  • t

    Tim Malseed

    10/27/2020, 1:08 AM
    I'm using Dispatchers.IO while reading data from files on disk. It can take anywhere from 1-5 mins to complete. But, it's using up basically all of the available resources. Is there a way to kind of cap the amount of work being done on a particular dispatcher?
    z
    t
    48 replies · 3 participants
  • t

    TwoClocks

    10/27/2020, 2:12 AM
    Is there a coroutine/suspending network library out there yet?
    s
    s
    +2
    10 replies · 5 participants
  • k

    kevin.cianfarini

    10/27/2020, 3:07 AM
    Is there a way to chain
    onEach
    with
    MutableStateFlow
    and return a
    MutableStateFlow
    ? My use case -- calling
    SavedStateHandle.getLiveData(key: String)
    will automatically save new emissions to that live data into the saved state. I would like something like this to be possible with StateFlow
    fun <T> SavedStateHandle.getStateFlow(key: String, defaultValue: T): MutableStateFlow<T> {
        return MutableStateFlow(this[key] ?: defaultValue).onEach {
            this[key] = it
        }
    }
    However,
    onEach
    returns a regular instance of
    Flow
    . Is this something that's been discussed? If not, I'm more than willing to open an issue.
    z
    5 replies · 2 participants
  • o

    Orhan Tozan

    10/27/2020, 8:57 AM
    When using
    BroadcastChannel
    in ViewModel in order to send events, I was using the non suspend channel.offer(..) to send them, but now with SharedFlow, there seems only be the suspending
    emit(...)
    method. Does that mean all BroadcastChannel usage's can be migrated from
    events.offer(...)
    to Sharedflow?
    viewModelScope.launch {
        events.emit(...)
    }
    If so, that looks like more boilerplate for simple events sending 😕
    b
    1 reply · 2 participants
  • p

    Paul Woitaschek

    10/27/2020, 2:52 PM
    Coroutines Riddle: What happens when you execute this with coroutines 1.4.0?
    inline class A(val value: String)
    
    fun main() {
        runBlocking {
            val aFlow = flowOf(A("Hello"))
            combine(aFlow, aFlow) { a, b ->
                a to b
            }.toList()
        }
    }
    t
    m
    5 replies · 3 participants
  • r

    Remy Benza

    10/28/2020, 8:27 AM
    I have a question about retriggering a flow (Android app with Paging 3)
    6 replies · 1 participant
  • l

    Lukas Lechner

    10/28/2020, 2:32 PM
    Hi! I created a “Kotlin Coroutines Exception Handling Cheat Sheet”. It might be helpful 👉 https://www.lukaslechner.com/coroutines-exception-handling-cheat-sheet/
    👍 11
    n
    e
    5 replies · 3 participants
  • b

    bsimmons

    10/28/2020, 6:35 PM
    Hey all, so I'm trying to work around an inconsistently slow API. What's the best way to make two async requests but only keep the fastest one to respond? (That infinite
    while
    seems like an antipattern to me.) Any ideas?
    example.kt
    l
    n
    +1
    15 replies · 4 participants
  • f

    Florian

    10/28/2020, 9:09 PM
    Has anyone here used the new Jetpack DataStore yet? I want to restore the checked state of a checkbox options menu item when a fragment is created. 1. I use
    first()
    because I only need to set the value from DataStore once, afterwards just clicking the checkbox will check/uncheck it. Does this make sense? Are there any situations where it will break? 2. Is the asynchronicity a problem? As far as I understand, you can't read from DataSore synchronously so this is the only option I can see.
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        
        [...]
        
        viewLifecycleOwner.lifecycleScope.launch {
            menu.findItem(R.id.action_hide_completed_tasks).isChecked =
                viewModel.preferencesFlow.first().hideCompleted
        }
    }
    l
    4 replies · 2 participants
  • p

    Pablo

    10/29/2020, 8:47 AM
    Hello why my flow is not catched when an exception is thrown? my flow is
    flow {
    val resultService = service.getWhatever()
    val mapStuff = resultService.mapper() <-- it throws NullPointer
    emit(mapStuff)
    }
    Then on my viewmodel I have
    usecase.execute(2)
    .catch{do something}
    .collect{expectedStuff}
    What I'm missing? Do I have to add a 
    .catch
      on my datasource so the viewmodel is aware something crashed?
    g
    r
    5 replies · 3 participants
  • a

    Adrian Blanco

    10/29/2020, 9:19 AM
    I recently migrated from
    PublishSubject.create<T>()
    to
    MutableSharedFlow<T>(replay = 0, extraBufferCapacity = 1)
    , but what I can't wrap my head around is what is the use case for
    MutableSharedFlow<T>()
    ? (both parameters set to zero by default). It doesn't really seem to do anything.
    g
    8 replies · 2 participants
  • f

    Florian

    10/29/2020, 10:54 AM
    To avoid using GlobalScope in my small project, I created this application scope provided by Dagger:
    @ApplicationScope
    @Provides
    @Singleton
    fun provideApplicationScope() = CoroutineScope(SupervisorJob())
    Should I also inject the dispatcher that is used with this scope, and why?
    g
    t
    6 replies · 3 participants
  • m

    Marko Kovacevic

    10/29/2020, 11:32 AM
    [Channels] Hi, everyone. Are channels stable? I'm getting experimental errors in InteliJ with latest coroutines dependency
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.0-M1")
    l
    g
    10 replies · 3 participants
  • c

    coder82

    10/29/2020, 1:12 PM
    Something weird happening here, I launch a coroutine on a single thread context and the profiler shows me it creates a thread, runs the coroutine and puts that thread in WAIT, so my app is leaking threads?
    m
    10 replies · 2 participants
  • f

    Florian

    10/29/2020, 3:33 PM
    I have a DialogFragment that executes some db delete operation (via its own ViewModel). Since a dialog dismisses immediately when you click a button, it makes sense to use applicationScope instead of viewModelScope, correct?
    class DeleteAllCompletedViewModel @ViewModelInject constructor(
        private val taskDao: TaskDao,
        @ApplicationScope private val applicationScope: CoroutineScope
    ) :
        ViewModel() {
    
        fun deleteCompletedTasks() = applicationScope.launch {
            taskDao.deleteCompletedTasks()
        }
    }
    i
    l
    11 replies · 3 participants
  • n

    nfrankel

    10/29/2020, 8:23 PM
    i’m a coroutine newbie and i’m stuck integrating co-routines and
    CompletionStage
    overall, my goal is to check whether i’ve an entity in the cache and if it’s not, go to the database the cache-checking returns a
    CompletionStage
    and the database repo is a suspending function how can i combine the two? the best i can do is:
    val person = cache.getAsync(id).await()
    return if (person == null) repository.findById(id)
    else person
    and obviously, it’s not the right way to do it i don’t find the correct operator help greatly appreciated 🙂
    j
    2 replies · 2 participants
  • f

    Florian

    10/30/2020, 10:54 AM
    I want to insert some initial items into my todo list. Is this the right place for a custom applicationScope or should I use GlobalScope?
    @Module
    @InstallIn(ApplicationComponent::class)
    object AppModule {
        private lateinit var database: TaskDatabase
    
        @Provides
        @Singleton
        fun provideDatabase(
            app: Application,
            @ApplicationScope applicationScope: CoroutineScope
        ): TaskDatabase {
            database = Room.databaseBuilder(app, TaskDatabase::class.java, "task_database")
                .fallbackToDestructiveMigration()
                .addCallback(object : RoomDatabase.Callback() {
                    override fun onCreate(db: SupportSQLiteDatabase) {
                        super.onCreate(db)
                        val dao = database.taskDao()
    
                        applicationScope.launch {
                            dao.insert(Task("Wash the dishes"))
                            dao.insert(Task("Do the laundry"))
                            dao.insert(Task("Buy groceries"))
                            dao.insert(Task("Call mom"))
                        }
                    }
                })
                .build()
            return database
        }
    
        @Provides
        @Singleton
        fun provideTaskDao(db: TaskDatabase) = db.taskDao()
    
        @ApplicationScope
        @Provides
        @Singleton
        fun provideApplicationScope() = CoroutineScope(SupervisorJob())
    }
    
    @Retention(AnnotationRetention.BINARY)
    @Qualifier
    annotation class ApplicationScope
    g
    10 replies · 2 participants
  • r

    Remy Benza

    10/30/2020, 11:50 AM
    How do I cancel a Flow collection and start a whole new flow?
    g
    l
    66 replies · 3 participants
  • o

    Oleksii Yerastov

    10/30/2020, 12:43 PM
    I’m in process of migration some parts of my codebase from Rx to coroutines and I wonder if I could get the similar behavior to
    private val subject = BehaviorSubject.create<Int>().startWith(Observale.just(1))
    but with
    SharedFlow
    for example? My use case is that I want to trigger specific function(in case of coroutines
    suspend
    function) only once during creation of
    SharedFlow
    or after first collector started collecting this flow. I cannot use
    onStart
    or
    onSubscription
    because there are more than 1 collector for this flow and thus, my specific function will be triggered for every collector. So as a result a want to end up with something like
    private val sharedFlow = MutableSharedFlow<Int>(replay = 1).startWith {
      // some suspending call that will be called only once
    }
    and also get
    MutableSharedFlow
    type for
    sharedFlow
    variable to be able to call
    emit
    /`tryEmit` for modification of cached value so all collectors get notified it changed. Is it possible to implement this behavior?
    j
    1 reply · 2 participants
Powered by Linen
Title
o

Oleksii Yerastov

10/30/2020, 12:43 PM
I’m in process of migration some parts of my codebase from Rx to coroutines and I wonder if I could get the similar behavior to
private val subject = BehaviorSubject.create<Int>().startWith(Observale.just(1))
but with
SharedFlow
for example? My use case is that I want to trigger specific function(in case of coroutines
suspend
function) only once during creation of
SharedFlow
or after first collector started collecting this flow. I cannot use
onStart
or
onSubscription
because there are more than 1 collector for this flow and thus, my specific function will be triggered for every collector. So as a result a want to end up with something like
private val sharedFlow = MutableSharedFlow<Int>(replay = 1).startWith {
  // some suspending call that will be called only once
}
and also get
MutableSharedFlow
type for
sharedFlow
variable to be able to call
emit
/`tryEmit` for modification of cached value so all collectors get notified it changed. Is it possible to implement this behavior?
j

Jeziel Lago

10/30/2020, 5:32 PM
My workaround:
fun <T> MutableSharedFlow<T>.startWith(
    action: suspend FlowCollector<T>.() -> Unit
) = object : MutableSharedFlow<T> {

    private val isFirstEmission = AtomicBoolean(true)
    override val replayCache: List<T> = this@startWith.replayCache
    override val subscriptionCount: StateFlow<Int> = this@startWith.subscriptionCount

    override suspend fun collect(collector: FlowCollector<T>) {
        if (isFirstEmission.compareAndSet(true, false)) {
            collector.action()
        }
        this@startWith.collect(collector)
    }

    override suspend fun emit(value: T) {
        this@startWith.emit(value)
    }

    override fun resetReplayCache() {
        this@startWith.resetReplayCache()
    }

    override fun tryEmit(value: T): Boolean = this@startWith.tryEmit(value)
}
maybe helps you
View count: 3