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

    fstn

    12/01/2017, 8:50 AM
    I think I done something wrong 😞
    AVERTISSEMENT io.netty.bootstrap.ServerBootstrap$ServerBootstrapAcceptor forceClose Failed to register an accepted channel: [id: 0x01a0436e, L:0.0.0.0/0.0.0.0:8080]
    java.lang.IllegalStateException
    	at io.vertx.core.net.impl.VertxEventLoopGroup.next(VertxEventLoopGroup.java:47)
    d
    • 2
    • 2
  • f

    fstn

    12/01/2017, 10:29 AM
    I miss something about Coroutine, it return Unit instead of my MutableList and I got this inside my logs:
    java.lang.IllegalStateException: Job StandaloneCoroutine{Completed}@6daf38a4 is already complete, but is being completed with kotlin.Unit]]`
    When calling:
    suspend fun getValidNextEvent(node: Node, messageBody: MessageBody): MutableList<Event<MessageBody>> {
    
            return suspendCoroutineOrReturn { cont ->
                val eventsToEmit = mutableListOf<Event<MessageBody>>()
    ....
                cont.resume(eventsToEmit);
            }
    
        }
    e
    • 2
    • 2
  • p

    Paul Woitaschek

    12/01/2017, 1:50 PM
    I'm really just interested in the latest offer
    d
    • 2
    • 2
  • k

    koufa

    12/01/2017, 2:04 PM
    How can I close a channel from which I am receiving values in a coroutine/suspend func as response to canceling the coroutine?
    l
    e
    • 3
    • 6
  • f

    fred.deschenes

    12/01/2017, 2:08 PM
    so I have a pretty weird use case, but has anyone ever had a "java.lang.VerifyError: Bad type on operand stack" exception when using coroutines?
    e
    • 2
    • 6
  • n

    nhellwig

    12/01/2017, 3:00 PM
    Hi, is there a way to also intercept when a coroutine suspends. I got it working for resume with the CoroutineInterceptor. The reason why I need this is for instructing the logging framework with fields (https://logback.qos.ch/manual/mdc.html) for logging.
    e
    • 2
    • 2
  • k

    koufa

    12/01/2017, 7:29 PM
    Is it possible to create a Deadlock passing down
    coroutineContext
    of a parent to child coroutines?
    e
    • 2
    • 1
  • f

    fstn

    12/02/2017, 7:30 AM
    Hi guys, how can I mock suspend function? For example, I would like to mock:
    val mockContextManager = Mockito.mock(ContextManager::class.java)
            Mockito.`when`(mockContextManager.get(1)).thenReturn(2)
    where get is a suspend function
    e
    • 2
    • 3
  • f

    fstn

    12/02/2017, 6:08 PM
    Do you have breakpoint issue inside suspend function? sometimes there are never call, or I can’t see variables ...
    e
    • 2
    • 2
  • m

    miha-x64

    12/03/2017, 2:10 PM
    In decompiled final class's code, I can see that
    suspend fun
    is
    open
    . What's going on, why?
    k
    o
    d
    • 4
    • 4
  • e

    elizarov

    12/04/2017, 12:02 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.20
    for Kotlin 1.2.0 with sequence-like extensions for channels, improvements to parent-child relations, more Android support and fixes. See full changes here: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.20
    🎉 36
    👏 20
    k
    p
    • 3
    • 12
  • k

    kevinherron

    12/04/2017, 11:21 PM
    upgrading to coroutines 0.20… mostly seamless 🙂 it also introduced a couple compilation errors, which was the first time an upgrade has done that
    e
    • 2
    • 3
  • e

    elizarov

    12/05/2017, 6:58 AM
    @kevinherron The approach with parent job suggest by @bj0 is indeed intended replacement if you need ability to cancel and join your actors. Alternatively, you should consider closing your actors via
    close
    that performs a graceful closing (letting actor finish all the processing). However, the
    close
    does not assume that you will be joining them.
    k
    • 2
    • 1
  • b

    bj0

    12/05/2017, 3:59 PM
    @elizarov i meant if you use
    close
    instead of cancel, so you let it finish all processing
    b
    • 2
    • 1
  • p

    pakoito

    12/05/2017, 10:05 PM
    with
    coroutineContext
    what do you mean in this context? literally accessing the field on your parent coroutine, if you’re in one of its blocks
    e
    • 2
    • 1
  • d

    dave08

    12/06/2017, 3:20 AM
    @elizarov But in the docs, it says that
    Unconfined
    is the equivalent of not using a scheduler in Rx, and it's very common, say in android, to want to run mainly on the current thread (with fan out/in, that SHOULD block the current thread only for the result), like in an IntentService that already has a working thread (that shouldn't stop until all tasks are finished, otherwise there could be leaks...)... in that case, is it better to use
    runBlocking
    or
    launch(Unconfined)
    , or is there no difference...? There's no clear rules about this in the docs, only 'hints' that seem a bit contradictory at times... Also, when is there a need for the top level
    yield
    function I mentioned before? Does it have to do with certain contexts being CorotineStart.dispatched by default or not?
    e
    • 2
    • 1
  • d

    dave08

    12/06/2017, 3:37 AM
    Say
    suspend fun getX()
    needs to be able to be run either in main thread context using
    CommonPool
    , or in an existing
    coroutineContext
    or in an already existing worker thread in a blocking fashion, depending on from where it's called, what's the recommended way to do each, and when would I have to
    yield
    ?
    e
    • 2
    • 3
  • d

    dave08

    12/06/2017, 3:43 AM
    With Rx, it's very simple and clear with
    subscibeOn
    and
    observeOn
    to do all this (but coroutines are much better in other aspects... 😉 ). In coroutines things seem much more complex in this aspect, and the 'danger' you mentioned... does that also exist in rx?
    e
    • 2
    • 1
  • e

    elizarov

    12/06/2017, 8:17 AM
    @dave08 The rule of thumb for coroutines is simple. If you have to ensure that certain code runs in a certain context (because it touches some confined shared mutable state like UI classes or because it is blocking), then you specify the context explicitly for this code. If your code is pure and does not care about its execution context (which should be true for most of the well-designed code) , then you leave the context specification out and go with default.
    d
    • 2
    • 10
  • l

    louiscad

    12/06/2017, 11:22 AM
    Hi, could anyone hint me at how I can convert an API with a God Callback to coroutines? This API is Bluetooth Low Energy GATT (General ATTribute) in Android, where you can only pass a
    BluetoothGattCallback
    instance with the overriden methods you'll need once, when connecting, and the connection result, the attributes discovery and read/write operations are passed to this callback. What I aim at is to use coroutines to handle failures without callback hell, in a procedural style, and to handle success this way too. The issue that I have is that this
    BluetoothGattCallback
    listens to too many different things. When connecting, I'm just interested in the connectionState callback. When writing data, I'm just interested in waiting for completion or error and knowing if it succeeded or failed, when reading data, just need the data, or exception... Is it possible to separate these things from this god callback? For reference, here is the key method with the two
    BluetoothGatt
    and
    BluetoothGattCallback
    key classes in its signature:
    <https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context>, boolean, android.bluetooth.BluetoothGattCallback)
    (select the whole link to get directed to the right method, slack doesn't like this url formatting) Please, reply in thread since this is quite specific to Android, so this channel doesn't get too cluttered
    e
    • 2
    • 5
  • r

    r4zzz4k

    12/06/2017, 11:51 AM
    @elizarov, I just wanted to shout out a big thank you! I just watched both your talks from kotlinkonf and they do really help with understanding coroutines both on low and high level. After them reading the guide is much easier. Great job on preparing and delivering the information, much appreciated!
    ➕ 6
    b
    • 2
    • 4
  • c

    camdenorrb

    12/06/2017, 3:44 PM
    Can you use CoRoutines on Kotlin onlinez?
    e
    • 2
    • 1
  • d

    dekans

    12/06/2017, 4:57 PM
    Silly question 😄 I'd like to
    await
    a block execution to not block the current thread, but I don't care about the result value. Is there a better practice for it than calling
    await()
    without using the result?
    t
    • 2
    • 3
  • d

    dave08

    12/06/2017, 5:29 PM
    Is the statement in the reactive guide:
    Note, that we can replicate the same behaviour that we saw with channels by using Rx publish operator and connect method with it.
    really true? In Rx,
    publish
    makes a
    ConnectableObservable
    which I would think is the equivalent of a
    BroadcastChannel
    ? Also is there a simple way of making a
    produce { }
    for a
    BroadcastChannel
    ?
    e
    • 2
    • 8
  • j

    jimn

    12/06/2017, 6:25 PM
    i like that but its not really different. slightly more terse. im doing asyncronous select hell, trying to channelize the inputs from disjunct packets to lines to headers to .. FSM progression. is there a "best" way to simply have var callback={it->....}; chan.foreach{callback(this)}
    d
    • 2
    • 1
  • a

    Arshak Ulubabyan

    12/06/2017, 8:09 PM
    Hi guys, I’m using Kotlin 1.2, tried to introduce coroutines to my application, but but I get this error: java.lang.NoClassDefFoundError: kotlin/coroutines/experimental/CoroutineContext$Element$DefaultImpls
    j
    • 2
    • 1
  • b

    bj0

    12/08/2017, 4:20 PM
    instead of
    while / try / receive
    you can just use a
    for
    loop over
    channel
    . As for testing,
    runBlocking
    is generally used to make the function wait until the coroutines are done.
    k
    • 2
    • 2
  • e

    elizarov

    12/09/2017, 12:52 PM
    Plain
    receive
    and
    for (x in channel)
    loop are both non-terminal
    l
    • 2
    • 1
  • k

    koufa

    12/09/2017, 10:16 PM
    So @elizarov I managed to test it but I had to remove the
    actor
    construct. Now I am calling the
    suspend
    fun
    loadProducts()
    from a
    runBlocking
    block directly. The question remains how I could make the
    runBlocking
    block to wait for the
    consumeEach
    in
    loadProducts()
    to finish, controlling somehow the mock
    channel
    I return from the mocked
    loadProducts()
    in my test. I hope I did explained it well. Thank you in advance for your interest.
    d
    • 2
    • 5
  • n

    nil2l

    12/11/2017, 10:53 AM
    You mean it can be done without such cache? Or just a common principle for run-like functions?
    g
    u
    • 3
    • 17
Powered by Linen
Title
n

nil2l

12/11/2017, 10:53 AM
You mean it can be done without such cache? Or just a common principle for run-like functions?
g

gildor

12/11/2017, 10:55 AM
produce created to allow write code inside of lambda, so all your sequence generation code will be encapsulated. But here you already have wrapper
NetworkCallStateProducer
and can just create channel and cache it to property
n

nil2l

12/11/2017, 10:56 AM
Ok, thanks.
Like this?
private val channel = Channel< NetworkCallState<T> >()
    fun getChannel(): ReceiveChannel< NetworkCallState<T> > = channel

    suspend fun produce() {

        do {
            val state: NetworkCallState<T> = suspendCoroutine { cont = it }
            channel.send(state)
        } while (!state.status.isCompleted())
        channel.close()
    }
g

gildor

12/11/2017, 11:20 AM
Why do you need suspendCoroutine there?
n

nil2l

12/11/2017, 11:23 AM
I work with an async API. New state (of network call) is coming via callback. I want to get
Channel<State>
for a call. I know sync calls should be used here. But currently I can use only async calls.
g

gildor

12/11/2017, 11:27 AM
Also, looks like you don't need
while
there, you just return channel. Also, you probably want something like BroadcastChannel to support multiple consumers, now you should create a channel for each consumer
But you can just call send on channel inside callback
n

nil2l

12/11/2017, 11:31 AM
No, I can’t. Callback has no coroutine context. It’s simply
(state) -> Unit
g

gildor

12/11/2017, 11:41 AM
Just use
offer
instead of
send
n

nil2l

12/11/2017, 11:42 AM
Wow! Nice. Thanks👍
Hm.. wait. I lose close() then. Though it may be not so bad –
getChannel().find { it.status.isCompleted() }
.
u

uli

12/11/2017, 8:32 PM
don't use
offer
.it might loose your `state`object if the consume is to slow
Using async network calls is exactly right for coroutines. You just might want to wrap it into suspend function like here: ~https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#wrapping-callbacks~
Then use that suspending function inside you producer
I guess that's pretty much what you already do, just with a little nicer abstraction. keeping the continuation magic isolated
Sorry for my unqualified comment 🙂 I missed that you have a series of state updates
How about calling
channel.send()
inside
run.blocking {}
inside your callback? There you have your coroutine context and depending on the network stack, you might even get back pressure, if the consumer is too slow.
View count: 5