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

    aballano

    04/04/2022, 12:27 PM
    Hello folks, I got the idea that catching and not rethrowing CancellationExceptions would be an anti-pattern but couldn't really find any documentation specifying that, does anyone know any docs saying this or any possible problems due to that? Thank you in advance!
    ➕ 1
    j
    r
    • 3
    • 5
  • s

    Slackbot

    04/04/2022, 3:01 PM
    This message was deleted.
    j
    t
    • 3
    • 13
  • t

    the great warrior

    04/04/2022, 4:27 PM
    I have a flow of type Boolean named selected and I want to get that value inside autoLocation Observer. how can I do that? , here's my code: PreferencesManager.kt
    class PreferencesManager(private val context: Context) {
                         ...
    val selected : Flow<Boolean>
            get() = context.counterDataStore.data.map { preferences ->
                preferences[AUTO_LOCATION] ?: false
               }
    }
    LocationFragment.kt
    class LocationFragment : Fragment() {
                       ...
          lifecycleScope.launch {
                mainViewModel.autoLocation.collectLatest {
                  //  check if selected      
                        it?.let {
                            mainViewModel.addPlaceItem(it)
                          }
                       }
                
              }
    }
    MainViewModel.kt
    class MainViewModel(
         private val application: Application
        private val placeRepository: PlaceRepository,
        private val preferencesManager: PreferencesManager,
    ) : ViewModel() {
                            ...
    val selected = preferencesManager.selected
    }
    m
    • 2
    • 2
  • r

    Robert Jaros

    04/04/2022, 5:27 PM
    https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.1
    :kotlin-intensifies: 3
    🎉 6
    o
    • 2
    • 1
  • s

    samp

    04/04/2022, 8:37 PM
    hey team, i am trying to bump kotlin coroutines 1.6.0 and see the following error:
    * What went wrong:
    Execution failed for task ':app:mergeDebugJavaResource'.
    > A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
       > 2 files found with path 'META-INF/kotlinx_coroutines_core.version' from inputs:
          - ../org.jetbrains.kotlinx/kotlinx-coroutines-core/1.6.0/c0277601cc4f7f24fe200651c5680e2e424a0a85/kotlinx-coroutines-core-1.6.0.jar
          - ../org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm/1.6.0/f3b8fd26c2e76d2f18cbc36aacb6e349fcb9fd5f/kotlinx-coroutines-core-jvm-1.6.0.jar
         Adding a packagingOptions block may help, please refer to
         <https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html>
         for more information
    I am adding this dependency:
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0
    I wonder who adds
    kotlinx-coroutines-core-jvm
    version? Is it included under
    kotlinx-coroutines-core
    ?
    j
    • 2
    • 2
  • l

    Lilly

    04/04/2022, 9:54 PM
    Is it possible to launch a coroutine in a flow operator?
    suspend fun producer() = flow {}
    
    private suspend packetFlow(...): Flow<ResponsePacket> {
      return producer()
         .transformWhile {
            // how to launch coroutine here that does not block?
            // coroutineScope {} blocks so it's not an option
            launch {
              delay(2000L)
              state = 1 // set state
              return@transformWhile false // terminate flow
            }
         }
    }
    I would like to start a timer and terminate the flow after time has expired.
    e
    • 2
    • 5
  • s

    Saiedmomen

    04/05/2022, 7:03 AM
    Why does the combine operator of flow works with arrays(instead of list or iterator)? From source code:
    public inline fun <reified T, R> combine(
        flows: Iterable<Flow<T>>,
        crossinline transform: suspend (Array<T>) -> R
    ): Flow<R> {
        val flowArray = flows.toList().toTypedArray()
        return flow {
            combineInternal(
                flowArray,
                arrayFactory = { arrayOfNulls(flowArray.size) },
                transform = { emit(transform(it)) })
        }
    }
    l
    • 2
    • 2
  • i

    ildar.i [Android]

    04/05/2022, 8:54 AM
    We have a search screen with paging 3. Each time a new word is typed we create a new flow with a new PagingSource doing api requests. How do I plug those new flows to my ViewModel flow? Right now I’m reEmiting them to my flow, but I’d rather reassign my flow to paging flow each time, which I can’t do
    j
    • 2
    • 2
  • h

    hfhbd

    04/05/2022, 12:01 PM
    With a
    suspend () -> Unit
    , you can create a
    Continuation
    by calling
    createCoroutine()
    . How can you create a
    CancelableContinuation
    ?
    s
    e
    k
    • 4
    • 8
  • i

    iamthevoid

    04/06/2022, 9:43 AM
    If
    Flow
    is stream and
    shared (state) flow
    is hot stream can i somehow sent
    completion
    event through?
    g
    c
    • 3
    • 3
  • a

    André Martins

    04/06/2022, 4:07 PM
    Hey guys, I have a piece of code which was making a single request to get something and then producing a calculation with the result. The first get (getPotatos) was taking around X milliseconds. But now I have to get two things and I’ve came up with the following solution. Although my problem is that now the first get is taking twice the time it was taking in first place. Is it possible that the way I’m doing the requests concurrently can affect each other?
    suspend fun getApples(): List<Apple> = ...
    
    suspend fun getPotatos(): List<Potato> = ...
    
    fun work(): ReceiveChannel<SomeResult> = GlobalScope.produce {
    
        try {
            val (apples, potatos) = coroutineScope {
                val getApples = async {
                    val (resp, time) = measureTimedValue {
                        getApples()
                    }
                    <http://logger.info|logger.info> { time.inWholeMilliseconds }
                    resp
                }
                val getPotatos = async {
                    val (resp, time) = measureTimedValue {
                        getPotatos()
                    }
                    <http://logger.info|logger.info> { time.inWholeMilliseconds }
                    resp
                }
                getApples.await() to getPotatos.await()
            }
    
    
            send(doSomething(apples, potatos))...
    
        } catch(ex: Exception) {
            handle...
        }
    }
    j
    • 2
    • 5
  • s

    samp

    04/06/2022, 11:25 PM
    Hey folks, Question about kotlin coroutines testing api in 1.6.0 when i should use
    val dispatcher = StandardTestDispatcher()
    val scope = TestScope(dispatcher)
    
    @Test
    fun testFoo() = runTest(dispatcher) {
        // ...
    }
    
    vs
    
    val dispatcher = StandardTestDispatcher()
    val scope = TestScope(dispatcher)
    
    @Test
    fun testFoo() = runTest {
        // ...
    }
    what if i don’t pass the dispatcher, I know it will default to
    StandardTestDispatcher
    but wouldn’t be those two different
    dispatcher
    here? 1. created by runTest 2. created by
    dispatcher
    property
    d
    j
    • 3
    • 5
  • q

    Quantum64

    04/07/2022, 2:38 AM
    Hi everyone. I'm trying to create a key-based mutex for the JVM. Can anyone tell me if this looks like a correct and safe implementation?
    class KeyedMutex<T> {
        @PublishedApi
        internal val mutexes = ConcurrentHashMap<T, Container>()
    
        data class Container(
            val mutex: Mutex,
            val holders: Int
        )
    
        suspend inline fun <U> use(key: T, closure: () -> U): U {
            val result = mutexes
                .compute(key) { _, container ->
                    container?.copy(holders = container.holders + 1)
                        ?: Container(Mutex(), holders = 1)
                }!! // always associates the key
                .mutex
                .withLock(action = closure)
    
            mutexes.computeIfPresent(key) { _, container ->
                if (container.holders > 1) container.copy(holders = container.holders - 1)
                else null
            }
    
            return result
        }
    }
    :thread-please: 2
    i
    e
    • 3
    • 6
  • o

    Omar Qadour

    04/07/2022, 5:11 PM
    Hi guys, where should i handle networking errors with the api in the MVVM pattern?
    i
    c
    • 3
    • 5
  • s

    samp

    04/07/2022, 7:23 PM
    What’s the best to do in tests? Use
    UnconfinedTestDispatcher
    and advance the coroutines automatically? or Use
    StandardTestDispatcher
    and manually execute the jobs? Do we have any recommendations from the official docs?
    ➕ 1
    j
    • 2
    • 1
  • s

    Sam Stone

    04/10/2022, 7:29 PM
    I have a download progress listener and want to conflate the results so only the latest progress is persisted to the db. I only have a callback
    override fun onProgress(Int)
    . Can I use a Flow for this?
    r
    • 2
    • 1
  • d

    darkmoon_uk

    04/11/2022, 8:22 AM
    Is there a way to observe a Job for changes in child jobs - so that we can potentially visualise a 'queue' of jobs - without having to further abstract?
    e
    • 2
    • 1
  • w

    William Reed

    04/11/2022, 12:24 PM
    what's the best way to emit the results of one flow into another? For example i am using a bluetooth library that has states for
    Connected
    and
    Disconnected
    as a
    StateFlow
    . I am trying to add more states such as
    Connecting
    or
    LookingForSavedDevice
    at a higher level in my program so I would like to use a
    StateFlow
    which both takes in emissions from the library functions as well as allow me to mutate the
    StateFlow
    myself. So I think I'm looking for a way to collect into another flow:
    bluetoothLibrary.stateFlow.collect(myOtherStateFlow)
    I'm aware I can just emit into the new flow in a
    collect { }
    block or
    onEach { }
    but I'm not sure what is canonical
    e
    • 2
    • 2
  • a

    Alexander Maryanovsky

    04/11/2022, 12:33 PM
    I have a long computation in a non-suspending function which consists of several transformations (map, reduce etc.) on a
    Sequence
    . How do I make this computation properly cancelable? All the Sequence functions are non-suspending, and the coroutine context is not available in a non-suspending function, so I can’t check for
    isActive
    . Can I capture the coroutine context in the outermost (suspend) function and pass it into all the (non-suspending) sequence functions?
    j
    • 2
    • 23
  • j

    juliocbcotta

    04/12/2022, 12:32 PM
    So, I have a list of tasks that I need to run based on their priority when the android app is launched. I would like to make the Main Thread wait the finish of these tasks execution, but I would like to delegate the execution to background threads....
    runBlocking(Dispatchers.Main.immediate) {
        initialize(application)
    }
    suspend fun initialize(app: Application) = coroutineScope {
        registry.groupBy { initializer ->
            initializer.priority().ordinal
        }
            .toSortedMap()
            .forEach { entry ->
                val tasks = entry.value.map { initializer ->
                    async {
                        initializer.initialize(app)
                    }
                }
                tasks.awaitAll()
            }
    }
    The code above runs, but if I change
    async {
    to
    async(Dispatchers.Default) {
    Makes the app blocks forever. Would anyone have an idea of how to fix it ?
    • 1
    • 1
  • m

    martmists

    04/12/2022, 2:24 PM
    Is there a way to use sequence {} with a suspend context? I'm using ktor to stream audio from an endpoint and would like to yield this in parts, but I get the error "Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope"
    s
    • 2
    • 1
  • j

    Ji Sungbin

    04/13/2022, 12:31 AM
    Hello, I am studying the internal working of coroutine. I have a simple function like below.
    fun main() = runBlocking {
     delay(1000)
     println("Bye, world!")
    }
    If decompile its bytecode into Java, will get the following output:
    public final class MainKt {
       public static final void main() {
          BuildersKt.runBlocking$default((CoroutineContext)null, (Function2)(new Function2((Continuation)null) {
             int label;
    
             @Nullable
             public final Object invokeSuspend(@NotNull Object $result) {
                Object var3 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
                switch (this.label) {
                   case 0:
                      ResultKt.throwOnFailure($result);
                      this.label = 1;
                      if (DelayKt.delay(1000L, this) == var3) {
                         return var3;
                      }
                      break;
                   case 1:
                      ResultKt.throwOnFailure($result);
                      break;
                   default:
                      throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
                }
    
                String var2 = "Bye, world!";
                System.out.println(var2);
                return Unit.INSTANCE;
             }
    
             @NotNull
             public final Continuation create(@Nullable Object value, @NotNull Continuation completion) {
                Intrinsics.checkNotNullParameter(completion, "completion");
                Function2 var3 = new <anonymous constructor>(completion);
                return var3;
             }
    
             public final Object invoke(Object var1, Object var2) {
                return ((<undefinedtype>)this.create(var1, (Continuation)var2)).invokeSuspend(Unit.INSTANCE);
             }
          }), 1, (Object)null);
       }
    }
    If the function end with
    return var3
    in
    case 0:
    in the code above, there should be a code that can enter the function again. I opened runBlocking and delay but couldn’t find it. Where are giving code to continue with label 1 ? (Sorry for the long code snippet)
    🤔 2
    e
    • 2
    • 2
  • e

    enighma

    04/13/2022, 8:27 AM
    If I get an exception for a coroutine scope, it’s marked as canceled even with a handler. What is the best practice to make another call with that scope? since it’s marked canceled my instinct is to create a new one, is that the preferred approach? I thought the handler would ensure it was not canceled, which doesn’t seem to be the case.
    s
    i
    • 3
    • 6
  • m

    Martin Rajniak

    04/13/2022, 8:52 AM
    Can anyone pls explain how come
    delay
    sometimes takes 30m instead of expected 4m (that were supplied as argument)? It is observed on Android.
    j
    l
    • 3
    • 5
  • h

    hfhbd

    04/13/2022, 10:35 AM
    IntelliJ (and dokka soon) shows a warning when using `suspend fun CoroutineScope.foo() { }`:
    Ambiguous coroutineContext due to CoroutineScope receiver of suspend function
    , because
    CoroutineScope.coroutineContext
    and
    coroutineContext
    . But why does coroutines-core itself use this construct? https://github.com/Kotlin/kotlinx.coroutines/blob/52cbf01c63c0737ee745ff08568f26385271a9ab/kotlinx-coroutines-core/common/src/Builders.common.kt#L50
    e
    • 2
    • 6
  • t

    Tom Everton

    04/13/2022, 11:38 AM
    Hey folks 👋, I’m relatively new to coroutines I have a question about coroutine scopes which I can’t seem to find a consistent answer for. Any input is appreciated! Say I have in an application I have two classes, an outer which will live for the whole lifecycle of the application and an inner class which is only alive for part of the lifecycle. For the outer class I create a coroutine scope which will be cancelled if the class is closed:
    class Outer : Closeable {
        private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
        private var inner: Inner? = null
    
        fun startInner() {
            inner = Inner(InnerRepo(), InnerApi())
        }
    
        fun stopInner() {
            inner.close()
            inner = null
        }
    
        override fun close() {
            scope.cancel()
        }
        ... // More code that uses the outer scope
    }
    And in the inner I have some code that calls suspend functions:
    class Inner(
        private val repo: InnerRepo,
        private val api: InnerApi
    ) : Closeable {
        private val innerScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob())    
    
        fun sendData() {
            innerScope.launch {
                api.sendData(repo.getData())
            }
        }
    
        override fun close() {
            innerScope.cancel()
        }
    }
    Is there a way to link the
    innerScope
    to the
    outerScope
    as it makes sense that the
    innerScope
    would always want to be cancelled if the outer scope cancels, or is that even something that should be done? Also, if the pattern above is completely wrong let me know! Cheers
    s
    e
    • 3
    • 6
  • n

    Nick Williams

    04/13/2022, 11:46 AM
    suspend fun main() {
    	coroutineScope {
       		flowOf<Unit>().shareIn(this, SharingStarted.WhileSubscribed())
        }
    }
    https://pl.kotl.in/gaJVXPMWr = Evaluation stopped while it's taking too long️. Why? The child coroutine of shareIn should, according to docs, never start
    e
    • 2
    • 4
  • l

    Lukasz Kalnik

    04/13/2022, 2:24 PM
    Is there a way to
    cancelAllChildren
    of a
    runTest
    scope? I have a test where I inject the test
    coroutineContext
    into a ViewModel and I want to cancel all running jobs inside the ViewModel when the test ends.
    t
    p
    • 3
    • 14
  • s

    Sanat Tripathi

    04/13/2022, 6:21 PM
    What is the best way to create a copy of a Map in Kotlin without causing ConcurrentModificationException in a multi-threaded environment? I almost would like
    map.toMap()
    to happen atomically. I wanted to see whether something exists before creating my own synchronization blocks.
    m
    e
    • 3
    • 2
  • a

    Ananiya

    04/14/2022, 3:58 AM
    any way to get rid of annoying channel cancellation exception i have rather simple code on VM that look like
    suspend fun get() = stateChannelFlow(viewModelScope){firebase.database./**some stuff*/.get.addOnSuccessListener { data ->
           viewModelScope.launch {
                send(data)
           }
       }
    }
    ik, you could say you should have used stateFlow instead ofstateChannelFlow I did but it forced me to use channel over regular flow btw called this function in Fragment() lifecycleScope at this time i have no idea if I messed the coroutine thing on get() but i tried my best trying d/n things which failed N: this is the code for the extension function
    suspend fun <T>stateChannelFlow(scope: CoroutineScope, @BuilderInference block: suspend ProducerScope<T>.() -> Unit): StateFlow<T> = channelFlow(block).stateIn(scope)
    g
    s
    • 3
    • 8
Powered by Linen
Title
a

Ananiya

04/14/2022, 3:58 AM
any way to get rid of annoying channel cancellation exception i have rather simple code on VM that look like
suspend fun get() = stateChannelFlow(viewModelScope){firebase.database./**some stuff*/.get.addOnSuccessListener { data ->
       viewModelScope.launch {
            send(data)
       }
   }
}
ik, you could say you should have used stateFlow instead ofstateChannelFlow I did but it forced me to use channel over regular flow btw called this function in Fragment() lifecycleScope at this time i have no idea if I messed the coroutine thing on get() but i tried my best trying d/n things which failed N: this is the code for the extension function
suspend fun <T>stateChannelFlow(scope: CoroutineScope, @BuilderInference block: suspend ProducerScope<T>.() -> Unit): StateFlow<T> = channelFlow(block).stateIn(scope)
g

gildor

04/14/2022, 4:00 AM
What are you trying to achieve here? I don’t see why you need channels in this case at all I’mn not sure how firebase API works here, but fir one time request you should instead write (or use existing) suspend function adapter, and for stream data see how existing adapters implemented and callbackFlow builder
Also there it’s not a good style to have a suspend function which returns Flow
If you share what kind types you want to use and how they work, I can help with adapter I actually surprised that there is no official firebase database adapter for coroutines
s

stojan

04/14/2022, 8:34 AM
as Andrey said,
callbackFlow
is the way... here is an example: https://piotrprus.medium.com/use-kotlin-coroutines-for-firebase-real-time-database-streams-e28d6083709c
g

gildor

04/14/2022, 9:33 AM
callbackFlow documentation itself has good example how to use it: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html
a

Ananiya

04/14/2022, 3:51 PM
Thanks,it was quiet frustrating but with a bit of research I found out I need to use firestore's await that allows me to get rid of channel flow and use
stateFlow
which was quite nice However it wasn't working as I wanted it I was expecting it to update the UI with stream of data change
Btw sorry for not mentioning the database i used it was firestore not FB R-T DB
g

gildor

04/16/2022, 2:15 AM
I was expecting it to update the UI with stream of data change
Maybe they have flow adapter? If they don’t you can write own with callbackFlow
View count: 13