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

    Vsevolod Ganin

    01/31/2020, 1:16 PM
    Hi. I’m getting
    w: Experimental API marker kotlinx.coroutines.FlowPreview is unresolved. Please make sure it's present in the module dependencies
    . I’m using
    allWarningsAsErrors = true
    so this stops my build. Is there any way to suppress this warning with compiler flag?
    • 1
    • 1
  • a

    antoniomarin

    01/31/2020, 2:13 PM
    Hello all, quite simple question, I’m experimenting a bit with coroutines, and I wonder what is the best approach to handle multiple endpoints inside single
    UseCase
    , I guess
    flow
    should be used?
    s
    • 2
    • 15
  • a

    audriusk

    01/31/2020, 3:57 PM
    I have test which pass successfully (expectation would be that it fails).
    @Test
        fun someTest() = runBlockingTest {
            Dispatchers.setMain(coroutineContext[ContinuationInterceptor] as CoroutineDispatcher)
    
            val viewModel = arrange()
    
            viewModel.viewModelScope.launch {
                throw IllegalStateException("mm")
            }
        }
    From my understanding problem is
    viewModelScope
    extension which creates
    SupervisorJob
    at https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:lifecycle/lifecycle-viewmodel-ktx/src/main/java/androidx/lifecycle/ViewModel.kt;l=42;drc=9f40e609cef60d1889e2b13d48ba1dbb8aa345e3 What would be appropriate way to make such test method fail?
    t
    a
    • 3
    • 6
  • d

    dimsuz

    01/31/2020, 4:36 PM
    Coroutine/KMPP question: what are my options if I want to send to the ConflatedBroadcastChannel from swift? Usecase: on button click in UI I want to send this click to the channel. But
    send
    is a suspending function and as such not usable from Swift/ObjC. Are there docs about this which I've missed? I see a lot of tutorials for iOS concurrency, but a little about this kind of interop. Not sure if this is the right channel as it is both about #coroutines and #multiplatform
    a
    • 2
    • 2
  • j

    Jabez Magomere

    02/03/2020, 1:31 PM
    I'm working on a codebase with both Java and Kotlin code, i introduced Kotlin coroutines to help in running background tasks, however i have a function in my repository marked with the keyword suspend and i call it from an Intent Service that is written in java to sync local db with remote. However i can only call a suspend function from another suspend function or a coroutine builder. I three options in mind: Option 1 Use GlobalScope.launch(Dispatchers.IO) on the function so that i can call it from the Intent Service. However GloablScope is not highly recommended in the android context. Option 2 Make my repository extend Coroutine Scope, create a public function called onCleared that cancels job, then call this function when the service onDestroyed method is called or when the view model onCleared method is called. This option is to try and cancel any running operations. Option 3 Use the viewmodel scope to launch the coroutine in the repository, then call the viewmodel from the service, however the viewmodel should only be limited to an activity or fragment. Option 4 Refactor the intent service to Kotlin and use coroutines
    4️⃣ 4
    m
    l
    +2
    • 5
    • 6
  • a

    Arkadii Ivanov

    02/03/2020, 10:27 PM
    BroadcastChannel
    drops items if there are no subscribers. Is there a way to not drop but buffer? Looking for something with
    UnicastSubject
    behaviour.
    g
    g
    • 3
    • 11
  • d

    Derek Berner

    02/03/2020, 10:44 PM
    Hi, how do you add
    kotlinx-coroutines-io
    as a dependency to the
    commonMain
    sourceset in a MPP project?
    l
    • 2
    • 1
  • a

    Abhishek Bansal

    02/04/2020, 10:12 AM
    Does
    BroadcastChannel#openSubscription.consumeAsFlow()
    completes when collected? If not how do I go about cancelling subscription? I was trying to do this in my class so that client does not have to worry about cancelling the subscription
    private fun getResponseChannel(): Flow<ContentResponse> {
            val channel = responseChannel.openSubscription()
            return channel
                .consumeAsFlow()
                .onCompletion {
                    Timber.d("Cancelled")
                    channel.cancel()
                }
        }
    But it seems that
    onCompletion
    never gets called
    d
    s
    • 3
    • 3
  • m

    myanmarking

    02/04/2020, 10:44 AM
    is it possible to check if there are active jobs within a coroutineScope ?
    j
    d
    t
    • 4
    • 6
  • g

    gotoOla

    02/04/2020, 2:57 PM
    If I have a class that implements CoroutineContext, how would I go about to perform a graceful shutdown? A graceful shutdown in this case meaning wait for any ongoing child to finish (so joinAll() on any child-coroutine spawned) It seems CouroutineConext.cancel() is quite aggressive and does cancel instead of join (which the name kinda indicates as well :P)
    z
    d
    +2
    • 5
    • 20
  • j

    Jabez Magomere

    02/05/2020, 6:43 AM
    Is it okay for a Service in android to extend Coroutine Scope?
    t
    l
    +2
    • 5
    • 4
  • f

    fatih

    02/05/2020, 9:43 AM
    What is the best way to handle
    Flow
    on device rotation in Android if you are only using
    Flow
    (without
    LiveData
    )? I see that Dropbox Store library caches the latest and provides when it is requested again. https://github.com/dropbox/Store
    The first time you call to suspend store.get(key), the response will be stored in an in-memory cache and in the persister, if provided. All subsequent calls to store.get(key) with the same Key will retrieve the cached version of the data, minimizing unnecessary data calls.
    Since the Flow is cold it is going to be collected evertime.
    s
    k
    z
    • 4
    • 9
  • s

    Slackbot

    02/05/2020, 10:25 AM
    This message was deleted.
    o
    k
    k
    • 4
    • 5
  • d

    dimsuz

    02/05/2020, 12:25 PM
    Hi! Coroutine + Multiplatform question. I have this code on Linux, using Kotlin/Native:
    class MyClass : CoroutineScope by MainScope() {
      fun execute() = launch {
        delay(1000)
        println("finished")
      }
    }
    
    fun main() = runBlocking {
      val clazz = MyClass()
      clazz.execute()
    }
    This throws an exception:
    kotlin.IllegalStateException: There is no event loop. Use runBlocking { ... } to start one.
    What do I do wrong? • If MyClass is external and I can't modify it, how to solve this? • For some reason if I run the code from the
    main()
    function in Android Activity (which doesn't even have any CouroutineScope), it runs perfectly well. Why?
    • 1
    • 1
  • m

    myanmarking

    02/05/2020, 3:23 PM
    basically, it's a timeout for flow, it closes after timedOut
    s
    d
    • 3
    • 7
  • d

    dave08

    02/05/2020, 4:57 PM
    How do I get the ---last--- element of a
    Flow
    without having to use
    toList().last()
    ...?
    j
    • 2
    • 5
  • j

    Joe

    02/05/2020, 7:41 PM
    What is generally stylistically preferred:
    class CoroutineJob {
        suspend fun doWork() {
              // do stuff in coroutine context
        }
    }
    // elsewhere:
    scope.launch { 
        CoroutineJob().doWork()
    )
    or
    class CoroutineJob(val scope: CoroutineScope) {
        fun launchWork() {
            scope.launch {
                // do stuff in coroutine context (possibly calling another suspend fun member?)
            }
        }
    }
    // elsewhere:
    CoroutineJob(scope).launchWork()
    or something else?
    1️⃣ 9
    b
    e
    • 3
    • 3
  • h

    hiperbou

    02/05/2020, 8:08 PM
    Hello, I would appreciate if someone could bring some light on this problem I'm having. I would like to get the result of a suspend function called using the invoke method inside a java Proxy's InvocationHandler. I reduced the problem to to a test, but I am still not able to figure out how to intercept the result inside the InvocationHandler's code. https://gist.github.com/hiperbou/283e6531fb2b71b324d5064f820df889
    o
    • 2
    • 3
  • r

    Remy Benza

    02/06/2020, 8:00 AM
    what are the benefits for using Flow from a Room query in Android as oppose to using Livedata?
    m
    t
    +6
    • 9
    • 21
  • d

    dave08

    02/06/2020, 5:25 PM
    If I have a conflated
    BroadcastChannel
    and I send something before using
    asFlow()
    on it, will I receive what was sent?
    z
    • 2
    • 5
  • u

    ubu

    02/07/2020, 11:00 AM
    Hi there. Need an advice. Inside a
    ViewModel
    , I had a basic MVI-inspired state machine implemented in the following way:
    /**
     * State machine for this view model consisting of [Interactor], [State], [Event] and [Reducer]
     * It reduces [Event] to the immutable [State] by applying [Reducer] fuction.
     * This [State] then will be rendered.
     */
    class Interactor(
            private val scope: CoroutineScope,
            private val reducer: Reducer = Reducer(),
            private val channel: Channel<Event> = Channel(),
            private val events: Flow<Event> = channel.consumeAsFlow()
        ) {
            fun onEvent(event: Event) = scope.launch { channel.send(event) }
            fun state(): Flow<State> = events.scan(State.init(), reducer.function)
        }
    
    interface StateReducer<STATE, EVENT> {
        val function: suspend (STATE, EVENT) -> STATE
        suspend fun reduce(state: STATE, event: EVENT): STATE
    }
    But then I was unable to get current state, I could only observe it as a
    Flow<State>
    , so I re-implemented it in the following manner:
    class Interactor(
            private val scope: CoroutineScope,
            private val reducer: Reducer = Reducer(),
            private val channel: Channel<Event> = Channel(),
            private val events: Flow<Event> = channel.consumeAsFlow()
        ) {
            
           val state = ConflatedBroadcastChannel<State>()
    
            init {
                scope.launch {
                    events.scan(State.init(), reducer.function).collect { state.send(it) }
                }
            }
    
            fun onEvent(event: Event) = scope.launch { channel.send(event) }
            fun state(): Flow<State> = state.asFlow()
        }
    I guess it could be improved. Are there any inherent problems to this implementation? Thanks a lot, in advance 💥.
    e
    a
    • 3
    • 23
  • k

    kevin.cianfarini

    02/07/2020, 10:39 PM
    does
    Channel.offer
    on a
    RendezvousChannel
    always return false? Or will it return true if a receiver is already waiting for the next value?
    o
    • 2
    • 2
  • n

    Nikky

    02/08/2020, 12:15 PM
    what is the shortest code to follow the
    same thread enforcement
    of a library? i need to store what thread something was created on and then switch back to it whenever interacting with it i just nee the right keyword to look for, not even sure what to look for
    g
    • 2
    • 2
  • g

    Gabriel Feo

    02/08/2020, 8:09 PM
    coroutines-android question: https://kotlinlang.slack.com/archives/C0B8M7BUY/p1581192521336600
    a
    l
    • 3
    • 6
  • r

    Robert

    02/09/2020, 3:11 PM
    Is having a reentrant readwrite lock an anitpattern in a reactive stack? Does it make sense to wrap it into a coroutines?
    a
    • 2
    • 4
  • k

    Konstantin Petrukhnov

    02/10/2020, 7:34 AM
    I'm trying to use ktor for many simultaneous of TCP connections on JVM. Each connection is tcp client to different ip/port, and amount of data would be quite low. Any suggestions of should there be single thread or multiple, pools, etc?
    v
    g
    • 3
    • 9
  • k

    kevin.cianfarini

    02/10/2020, 3:53 PM
    Is there any reason that
    channelFlow
    doesn't expose something like
    fun channelFlow(buffer: Int = ...)
    And instead we have to call
    .buffer
    downstream?
    👀 1
    z
    • 2
    • 5
  • k

    kevin.cianfarini

    02/10/2020, 3:56 PM
    I also don't know the performance implications of that since we're creating an extra channel and flow to wrap the one upstream
    z
    • 2
    • 2
  • k

    kevin.cianfarini

    02/10/2020, 4:13 PM
    IS the corotuines team open to community PRs? I have a rx operator analog for flow that is missing
    z
    g
    • 3
    • 2
  • g

    gergo

    02/10/2020, 4:22 PM
    If you have a
    suspend fun
    annotated with
    @Throws(IOException::class)
    , then the IDE will signal an “Inapropiate blocking method call”, even if the called method runs on the IO dispatcher. Example:
    suspend fun testCall(uri: Uri) {
        val image = encodeImageToBase64(uri)
    }
    
    @Throws(IOException::class)
    private suspend fun encodeImageToBase64(imageUri: Uri): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        // Do something
        ""
    }
    (Android Studio 3.6-rc02, kotlin version: 1.3.50/1.3.61) I am not sure why this warning is shown in such case? Could this be a lint issue or am I missing something?
    b
    k
    • 3
    • 2
Powered by Linen
Title
g

gergo

02/10/2020, 4:22 PM
If you have a
suspend fun
annotated with
@Throws(IOException::class)
, then the IDE will signal an “Inapropiate blocking method call”, even if the called method runs on the IO dispatcher. Example:
suspend fun testCall(uri: Uri) {
    val image = encodeImageToBase64(uri)
}

@Throws(IOException::class)
private suspend fun encodeImageToBase64(imageUri: Uri): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    // Do something
    ""
}
(Android Studio 3.6-rc02, kotlin version: 1.3.50/1.3.61) I am not sure why this warning is shown in such case? Could this be a lint issue or am I missing something?
b

Brandon Trautmann

02/10/2020, 4:37 PM
If it's an Android lint issue, there will be an issue ID along with the warning
🙏 1
👍 2
k

Kroppeb

02/10/2020, 11:09 PM
It's nothing to worry about. It thinks you are calling a java function that would block the thread. The compiler isn't advanced enough yet to see you properly wrapped your call.
👍 1
🙏 1
View count: 3