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

    Dimitri Fedorov

    07/08/2019, 7:33 PM
    Hello guys. I’m trying to escape callback hell in my current application, and it seems I can’t find proper coroutine-based approach. Almost all existing code is following this pattern:
    element.call() {
       service.run() {
          element2.call() { ... }
       }
    }
    there is 2 requirements: 1. every element or service is invoking callback on proper thread already 2. every call shouldn’t block its own thread, i.e. each callback should exit after invoking next element/service (i can’t use
    suspendCoroutine
    because of that) what is proper coroutine way to do that?
    s
    z
    +2
    56 replies · 5 participants
  • p

    Paul Woitaschek

    07/09/2019, 8:01 AM
    When I wrap a single value in a flow: Is there a better way than writing
    flow { emit(mySuspendingFunction()) }
    ?
    d
    d
    +1
    7 replies · 4 participants
  • d

    Derek Berner

    07/09/2019, 1:06 PM
    If I create a new coroutine context and use
    withContext
    to
    launch
    a bunch of `Job`s in that context, does that mean I don't have to explicitly
    join
    all those jobs at the end of the block?
    d
    b
    16 replies · 3 participants
  • p

    Paul Woitaschek

    07/09/2019, 2:49 PM
    https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/lifecycle/lifecycle-viewmodel-ktx/src/main/java/androidx/lifecycle/ViewModel.kt Why don't they cancel the scope directly but instead get a reference to the context and cancel that only?
    s
    7 replies · 2 participants
  • s

    streetsofboston

    07/09/2019, 3:33 PM
    I have a question on how Exceptions are handled in Coroutines that run within a
    SupervisorJob
    . To me it seems the code has a bug in how exceptions propagate (or not) to the parent of a Coroutine run within a SupervisorJob. I logged the issue here: https://github.com/Kotlin/kotlinx.coroutines/issues/1317 Can someone shed a light on how this is supposed to work? I’m a bit baffled 🙂 Thanks!
    m
    e
    3 replies · 3 participants
  • b

    bj0

    07/09/2019, 11:45 PM
    if I have a
    Flow
    of data that has separators in it, is there an easy way to split it into a flow of separated chunks? ie:
    "@some data@more data@
    ->
    [some data, more data]
    j
    z
    +2
    29 replies · 5 participants
  • p

    pablisco

    07/10/2019, 8:13 AM
    What do you good people think of this? https://twitter.com/pablisc0/status/1148866357188055040?s=19
    ➕ 2
    g
    h
    +4
    24 replies · 7 participants
  • k

    koufa

    07/10/2019, 9:54 PM
    What's the difference betwenn
    channelFlow
    and
    callbackFlow
    ?
    e
    1 reply · 2 participants
  • e

    eygraber

    07/11/2019, 2:45 AM
    I've been getting a warning for the following code. The warning is:
    Non-applicable call for builder inference
    and it occurs on the line that starts with
    channel.send
    override val animationProgressChannel: ReceiveChannel<Float> = resumeScope.produce {
        lottieAnimation.addAnimatorUpdateListener { animation ->
          resumeScope.launch {
            channel.send(animation.animatedValue as Float) // Non-applicable call for builder inference (channel is highlighted)
          }
        }
      }
    If I change it to
    resumeScope.produce<Float>
    the warning goes away, but the IDE suggests that I "remove the explicit type arguments". Anyone know what's up with that?
    r
    g
    +1
    7 replies · 4 participants
  • c

    Cyrille QUÉMIN

    07/11/2019, 11:18 AM
    Hey guys, kotlin co routine multiplatform mentioned that it is single thread (js style) on native platform. Is it exactly like JS with a delegation principal to a background thread? Or does everything solely run on the main thread ??? If so. Is there a way to "hook" it up to iOS dispatch system in order to have at least one more thread to be able to do computation in the background and updating progress on the main thread for example?
    b
    k
    13 replies · 3 participants
  • a

    Antimonit

    07/11/2019, 11:30 AM
    I came across a problem that I cannot figure out how to achieve using coroutines. I have two
    async
    coroutines that both return the same type. I want to return only the value of the coroutine that finishes first and discard the value of the slower one. I have found that
    select
    takes care of selecting and returning value the faster coroutine but the other one is not cancelled and coroutineScope waits until the other one returns too. What would be the best approach?
    z
    j
    5 replies · 3 participants
  • k

    koufa

    07/11/2019, 12:17 PM
    Hello guys, I was trying out flow and did implement following example:
    flowOf("one string", "second string", "third string")
                .debounce(300)
                .map { it.trim() }
                .filter { it.length > 2 }
                .flowOn(Dispatchers.Default)
                .distinctUntilChanged()
                .switchMap {
                    // Simulate server call
                    delay(2000)
                    flow {
                        // Just return search term for the moment
                        emit(it)
                    }
                }
                .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
                .collect {
                    _viewState.value = it
                }
    Now I want to define a unit test for that but I am not sure how to do this for the above flow. Do I need to extract the flow except from the
    collector
    at the end to a function and then add a test
    collector
    and verify the values I would expect to get there? Or is there any other idiomatic way?
    s
    3 replies · 2 participants
  • w

    Wilson Castiblanco

    07/11/2019, 3:21 PM
    how soon cease to be Flow an experimental API?
    t
    1 reply · 2 participants
  • a

    alex.hart

    07/11/2019, 4:36 PM
    Could someone give me a hint on how to do multicasting with flow? (Multiple subscribers, possibly after flow has finished emitting items, like what
    cache
    or
    replay
    would do from Rx)
    s
    z
    7 replies · 3 participants
  • r

    rocketraman

    07/11/2019, 5:04 PM
    Under what situations can a thread using
    runBlocking
    remain parked, even though the underlying coroutines are no longer running?
    z
    g
    +1
    16 replies · 4 participants
  • s

    sam

    07/11/2019, 8:01 PM
    In other words,
    flow.grouped(10)
    // should give me List<T> now for each element, containing 10 elements except for the last list`
    j
    3 replies · 2 participants
  • d

    Daniel

    07/12/2019, 7:07 PM
    Hi guys and a big thanks in advance: I want to solve the following problem and I honestly don't know where to start googling it 😕 Lets say we have a database class and it has two methods:
    class Database {
        fun prefillDatabase() {
          // launch a non blocking job here that puts some data in the database
          // image this is done on application start
        }
    
        suspend fun getEntities() {
          // launch a blocking coroutine to get all entities of the database but only AFTER the job in prefillDatabase() completed
          // imagine this is called later in the application on button click.
        }
    }
    Is this a case for .join()? The job started in prefillDatabase() could already be well completed before getEntities() is called
    :yes: 1
    s
    o
    +1
    8 replies · 4 participants
  • k

    Kulwinder Singh

    07/13/2019, 11:49 AM
    How can make this network calls run simultaneously using Retrofit and Coroutines
    Retrofit_calls_simultaneously.kt
    s
    s
    10 replies · 3 participants
  • a

    Adriano Celentano

    07/13/2019, 1:29 PM
    someone knows a good open source project doing redux / mvi with coroutines ? just hacked together a very simplified experiment. As i am very new to coroutines i would be curious what there could be done better on the context of coroutines usage https://gist.github.com/AdrianoCelentano/d6d5833207a2a9db6c7fcfe3e9d67ca0
    a
    u
    3 replies · 3 participants
  • j

    Jag

    07/14/2019, 4:55 AM
    I’m writing some tests that require a bit more fine grained control around advancing the dispatcher’s clock by using
    runBlockingTest
    but it seems to eagerly execute despite invoking
    pauseDispatcher()
    I tried out the sample provided on the kotlinx-coroutines-test documentation but still hitting similar problems. I’m wondering if there’s just something I’m overlooking here? Here’s what I’m running from the documentation sample:
    @Test
        fun testFooWithPauseDispatcher() = runBlockingTest {
            pauseDispatcher {
                foo() // <-- this is still eagerly executed
                // the coroutine started by foo has not run yet
                // runCurrent() // the coroutine started by foo advances to delay(1_000)
                // the coroutine started by foo has called println(1), and is suspended on delay(1_000)
                // advanceTimeBy(1_000) // progress time, this will cause the delay to resume
                // the coroutine started by foo has called println(2) and has completed here
            }
        }
    
        fun CoroutineScope.foo() {
            launch {
                println(1)   // executes after runCurrent() is called
                delay(1_000) // suspends until time is advanced by at least 1_000
                println(2)   // executes after advanceTimeBy(1_000)
            }
        }
    a
    3 replies · 2 participants
  • f

    farzad

    07/14/2019, 11:16 AM
    If I run this:
    import kotlinx.coroutines.*
    
    fun main(args: Array<String>) {
        runBlocking {
            withTimeout(1300L) {
                repeat(1000) { i ->
                     println("I'm sleeping $i ...")
                    delay(500L)
                }
            }
        }
    }
    then I'll get this output:
    I'm sleeping 0 ...
    I'm sleeping 1 ...
    I'm sleeping 2 ...
    Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms
     at kotlinx.coroutines.TimeoutKt.TimeoutCancellationException (Timeout.kt:126) 
     at kotlinx.coroutines.TimeoutCoroutine.run (Timeout.kt:92) 
     at kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run (EventLoop.kt:307) 
     at kotlinx.coroutines.EventLoopImplBase.processNextEvent (EventLoop.kt:116) 
     at kotlinx.coroutines.DefaultExecutor.run (DefaultExecutor.kt:68) 
     at java.lang.Thread.run (Thread.java:745)
    But if I run this one:
    import kotlinx.coroutines.*
    
    fun main(args: Array<String>) {
        runBlocking {
    		launch{
                withTimeout(1300L) {
                    repeat(1000) { i ->
                        println("I'm sleeping $i ...")
                        delay(500L)
                    }
                }
            }
        }
    }
    I'll get another output:
    I'm sleeping 0 ...
    I'm sleeping 1 ...
    I'm sleeping 2 ...
    why the second one doesnot throw exception?
    s
    g
    4 replies · 3 participants
  • d

    Dico

    07/14/2019, 11:20 AM
    Yesterday I ran into a bug with
    runBlocking
    In my program I have a top level coroutine dispatcher that uses
    runBlocking
    as an event loop for the main thread. In the application code, it uses
    runBlocking
    somewhere else for something more trivial. It seems that the dispatcher for the 2 contexts are sharing some state. It runs a few main loop frames when the second
    runBlocking
    is called. Moreover, the stacktrace in intellij, which says async stack trace, doesn't indicate any difference when the main loop is executed in this way.
    g
    5 replies · 2 participants
  • f

    farzad

    07/14/2019, 12:32 PM
    @channel any idea about this? https://kotlinlang.slack.com/archives/C1CFAFJSK/p1563102979226700
    s
    1 reply · 2 participants
  • t

    thana

    07/14/2019, 1:41 PM
    what are the rules of thumb about when to make a function
    suspend
    or just call a coroutine from within that method?
    s
    16 replies · 2 participants
  • a

    Alexjok

    07/14/2019, 8:27 PM
    it is possible with simple pipeline? Without adding channels and etc
    o
    g
    7 replies · 3 participants
  • t

    thana

    07/15/2019, 12:06 PM
    i tried to start my application with
    -javaagent:kotlinx-coroutines-debug-1.2.2.jar
    but then i got
    java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
    . any idea what i am doing wrong?
    d
    2 replies · 2 participants
  • g

    groostav

    07/15/2019, 8:54 PM
    has anybody got a good description of how mockito (and or some nice extension for it) can/should/will handle mocking `suspend fun`s? I remember mockito 1.X (1.95?) simply wouldn't, but now I notice that I've got 2.23 on my classpath. Does that automagically handle mocking suspend-funs for me?
    s
    b
    +2
    7 replies · 5 participants
  • d

    Dominaezzz

    07/16/2019, 9:02 AM
    Is it okay for java code to pass an instance of
    Continuation
    to a kotlin suspend function? Isn't it pretty much the same as using callbacks?
    g
    4 replies · 2 participants
  • t

    tseisel

    07/16/2019, 12:50 PM
    Since the inception of
    Flow
    , I am somewhat confused about when I should use
    Flow
    VS `Channel`s and `actor`s. I know that
    Flow
    represents a cold stream of values, but that stream can also be generated from a hot source, making it a deferrable hot stream. Do you have some specific use cases where you'd use `Channel`s over
    Flow
    , and why ? It seems to me that
    Flow
    can handle most use-cases.
    e
    z
    6 replies · 3 participants
  • u

    ursus

    07/16/2019, 1:04 PM
    if I run GlobeScope.launch from android view model, I leak it, right?
    s
    t
    +1
    53 replies · 4 participants
Powered by Linen
Title
u

ursus

07/16/2019, 1:04 PM
if I run GlobeScope.launch from android view model, I leak it, right?
s

streetsofboston

07/16/2019, 1:09 PM
It depends, but yes, you run that risk.
u

ursus

07/16/2019, 1:10 PM
but how can I just detach the reference, so it doesnt leak, yet complete the upstream suspend functions?
if I cancel the job it cancels everything
t

tseisel

07/16/2019, 1:23 PM
What is your use case, so that you need the launched job to outlive your ViewModel ?
u

ursus

07/16/2019, 1:24 PM
data sync, which does some api calls and then writes to database
s

streetsofboston

07/16/2019, 1:31 PM
Yup, you want the request to continue even if the user cancels the screen, so that you could cache it. Use your view-model scope for your requests from your UI/ViewModel. Then in your service/datasource implementation use your own 'global' scope (
CoroutineScope(...)
) and switch to it for running and caching your request.
Maybe something like this?
class MyViewModel : ViewModel() {
    ...
    viewModelScope.launch {
        ...
        val result = service.getDataFromNetwork(input) 
        liveData.value = result.toUiResult()
    }
    ...
}

class ServiceImpl : Service {
    private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)

    override suspend fun getDataFromNetwork(input: String): NetworkResult = coroutineScope {
        scope.async { 
            val result = ... get result from network...
            addResultToCache(result)
            result
        }.await()
    }
}
☝️ 1
u

ursus

07/16/2019, 1:52 PM
interesting, ill try that out
s

streetsofboston

07/16/2019, 1:52 PM
In the above example, if the user has exited the screen before the network returns a result, the
liveData.value = result.toUiResult()
will never be called, because
viewModelScope
was cancelled. However, the
scope
in
ServiceImpl
is not cancelled. The
async
it launches runs until its completion.
u

ursus

07/16/2019, 1:52 PM
btw, is there a way for the viewmodel to connect back to the getDataFromNetwork, in case viewmodel (new instance of the same) comes back sooner than it returns?
async is like launch that returns a T ?
s

streetsofboston

07/16/2019, 1:54 PM
No. you'd have to create code that hooks up to the
ServiceImpl
and let
ServiceImpl
manage wether to get the data from the network or wait if the network request is still going or getting it from the cache/db
async
returns a
Deferrable<T>
, which is a sub-class for a
Job
.
u

ursus

07/16/2019, 1:55 PM
k, thanks, how would I do the connecting? pass result to a channel which viewmodel observes?
t

tseisel

07/16/2019, 1:56 PM
It seems to me that data-sync is better done with
WorkManager
: you schedule the task in the
ViewModel
, but it is run in the scope of the
Worker
. Therefore, the task is guaranteed to run to completion even if the
ViewModel
is cleared.
u

ursus

07/16/2019, 1:57 PM
@tseisel why would I need some android api for this? its scoping, viewmodel is just an concrete example use case
s

streetsofboston

07/16/2019, 1:58 PM
Using a Channel is a way. But be careful, you'd have to cache the network-request based on a a key (depends on the input to the request). It is not trivial. Instead of a Channel you could also cache `Deferrable<T>`s returned by the
async
calls with the request's input as the key. You can call
await()
on a
Deferred
multiple times. It will only run the
async
once, the other times it will return the already obtained result.
u

ursus

07/16/2019, 1:58 PM
you jhust need a scope that doesnt die with viewmodel (or whatever is the call site) like @streetsofboston demonstrated, however im not sure how to bridge those scopes yet
@streetsofboston okay so I need some kind of a mini database / store / map to keep the state and then expose channel / deffered somehow to the call site?
would that deffered contain erros as well?
s

streetsofboston

07/16/2019, 2:04 PM
class ServiceImpl : Service {
    private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
    private val cachedResults = mutableMapOf<Any, Deferred<*>>()

    override suspend fun getDataFromNetwork(input: String): NetworkResult = coroutineScope {
        var deferredResult = cachedResult[input] as Deferred<NetworkResult>
        if (deferredResult == null) {
            deferredResult = scope.async { 
                val result = ... get result from network using 'input'...
                result
            }
            cachedResults[input] = deferredResult
        }
        deferredResult.await()
    }
}
And
await()
will throw an Exception if teh result was an exception
The above code is just an idea... may not entirely compile and may not be thread-safe with regards to
cachedResults
. Also, you'd need a way to clean up the cache when necessary.
u

ursus

07/16/2019, 2:06 PM
Looks interesting, but im not sure about the call site, that would mean youd call getDataFromNetwork "locally" from some button click proxied function or whatever
but then again in viewmodel.init to get the possible cached value again, right?
s

streetsofboston

07/16/2019, 2:08 PM
The call-site, where
viewModelScope
launches its thing, is wherever you need it. I don't know where that would be, depends on your use-case. It could be in the
init { ... }
block of your ViewModel, or on a button-click when your Fragment/Activity calls to a method on your ViewModel, etc.
u

ursus

07/16/2019, 2:09 PM
like this right?
ViewModel {
	val liveData

	fun syncButtonClicked() {
		viewModelScope {
			val result = service.getDataFromNetwork()
			withContext(UI) {
				liveData.set(result)
			}
		}
	}
}
if so, then to reconnect youd need this
ViewModel {
	val liveData

	init {
		viewModelScope {
			val result = service.getDataFromNetwork(SYNC_KEY)
			withContext(UI) {
				liveData.set(result)
			}
		}
	}

	fun syncButtonClicked() {
		viewModelScope {
			val result = service.getDataFromNetwork(SYNC_KEY)
			withContext(UI) {
				liveData.set(result)
			}
		}
	}
}
right? Isnt that a bit odd?
s

streetsofboston

07/16/2019, 2:11 PM
When do you need to reconnect, though?
u

ursus

07/16/2019, 2:12 PM
say you want to display a progressbar while sync is in progress .. so after leaving the viewmodel and coming back to it again, it should show right away if sync in progress
s

streetsofboston

07/16/2019, 2:14 PM
But yes, something like that, if you need to reconnect. Remember, viewModelScope already runs in the UI thread, no need to do
withContext(Dispatchers.Main)
. Also, I don't see any call to
launch
and such in your code.... Note that your
init
block issues the request, even if the user has not pushed the button before.... you'll need another method on
Service
(and
ServiceImpl
) that queries if a cached Deferred<T> exists or not and if so, only then waits for it.
u

ursus

07/16/2019, 2:19 PM
Yea, dammit..seems like a Channel with status of Idle, InProgress right? however, if I "sideffect" to the channel, I lose suspend function composability right? i.e. I exit the coroutine world?
s

streetsofboston

07/16/2019, 2:27 PM
You can also just add a method to
Service
, called something like
queryDataFromNetwork(...)
that just awaits a result if the
cachedResults
has a Deferred entry for the given input and returns immediatly
null
if has no such entry. Not sure what you mean with 'composability'. If you mean make it functional by composing lambdas/functions, I would do that later when stuff works. :-) If you need status updates, like 'idle', 'progress', 'loading', ..., 'result', then a channel is better suited.
u

ursus

07/16/2019, 2:27 PM
So..not sure if its good, since you then "hardcode" that service/repository whoever to be the leaf node of the couroutine
s

streetsofboston

07/16/2019, 2:27 PM
Why is that not good?
u

ursus

07/16/2019, 2:29 PM
by composability I mean being able to just call suspend functions as normaln imperative code
since If we were to use the channel, that means most likely that getDataWhatever (rename to fetchDataWhatever) should be nonsuspending and return Unit
no?
s

streetsofboston

07/16/2019, 2:30 PM
Your service would return a Channel (a ReceiveChannel), not Unit
For composabitilty: You can call suspend functions as normal sequential/imperative code... as long as you do it inside a Coroutine (the lambda of a
launc
or
async
)
u

ursus

07/16/2019, 2:33 PM
no no I mean like this
ViewModel {
	val liveData

	init {
		viewModelScope {
			service.syncStatusChannel.receive {
				withContext(UI) {
					liveData.set(result)
				}
			}
		}
	}

	fun syncButtonClicked() {
		service.fetchDataFromNetwork()
	}
}


class ServiceImpl : Service {
	private val _syncStatusChannel = MutableChannel
	syncStatusChannel : Channel
		get() = _syncStatusChannel

    private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)

    override fun fetchDataFromNetwork(input: String): Unit = coroutineScope {
    	_syncStatusChannel.send(IN_PROGRESS)
        val result = ... get result from network...
        addResultToCache(result)
        _syncStatusChannel.send(IDLE)
    }
}
I dont know the coroutines api just yet so I made up the channels api 😄 hopefully its readable
s

streetsofboston

07/16/2019, 2:38 PM
Something like that would be possible, yes.
receive
would be
consumeEach
. And not
viewModeScope { ... }
, but
viewModelScope.launch { ... }
instead.
And no need to do
withContext(UI)
there either, since
viewModelScope
already uses the Main-UI dispatcher.
u

ursus

07/16/2019, 2:39 PM
Okay thanks, but the main issue is that the trigger functions returns Unit and is nonsuspending..should it? since now it cannot be used in coroutines to "do something after fetch completed" right?
s

streetsofboston

07/16/2019, 2:42 PM
Creation and obtaining Channels don't need Coroutines/Suspend-funs. Writing to them and reading from them, though, can only happen in a Coroutine/Suspend-fun. Before using Channels, go to their documentation on JetBrains and use them appropriately. Lots of interesting ways of using them. And maybe you'd want to use a
Flow
instead of a
Channel
u

ursus

07/16/2019, 2:46 PM
obtaining channel is fine, what I mean mainly is the trigger function, should it return plain nonsupsending Unit or some kind of coroutine thing?
what I fear is if I sideffect the status into the channel, i'll lose the composability of the trigger fetchData function
Which then hardcodes that service to be a leaf in that layer, which is fine if its only used by viewmodels (since those are only in lower scope)
but what if Id want some other repository to call the fetch and do somethiny after fetch completes (regular corutine use case)
s

streetsofboston

07/16/2019, 2:52 PM
Showing a loading/waiting spinner is a side-effect; you write something to an external device, the UI/screen in this case. There are other ways to do this without a Channel and separating the side-effects, impure code, from the 'pure' code. E.g. use a
suspend
fun to get the actual data in a Coroutine `launch`ed by your ViewModel and that code will then update a
LiveData
property as well that is tied to a waiting/loading-spinner.
z

zhuinden

07/16/2019, 4:07 PM
@ursus why not call the
GlobalScope.launch {
inside a singleton instead of from ViewModel directly? Then it won't have a reference to your ViewModel and won't be able to leak. You could use something like an event bus (channels?!) to communicate back.
u

ursus

07/16/2019, 4:08 PM
well..yes..but I thought you couldnt then have it as a suspend function, ill post some code later after I try it
View count: 6