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

    zak.taccardi

    09/10/2020, 8:43 PM
    given a
    Job
    , how can I fail it with an exception? I want to cancel it abnormally so its parent fails
    z
    • 2
    • 17
  • t

    taer

    09/10/2020, 9:21 PM
    I have this http api that I'm trying to make beautiful. It's paginated, and any api call(page 1,2,3,4,5 etc) could 429. So I have N queries that I'm converting via a helper into a flow of the entities themselves. So callers get a Flow of entities instead of having to implement the loop logic. In the example I'm linking, it's a "service" that have 10 pages of Integers that it returns. It fails randomly. The structure is a flow that
    emitAll
    a flow that has the retry appended. Again, it's all working perfectly, but something seems just off about it.. Seems like too many flows. Thanks https://pl.kotl.in/ysrpoKNa7
    t
    • 2
    • 3
  • a

    Allan Wang

    09/11/2020, 8:12 AM
    Can we build jars with a main class having
    suspend fun main
    , or do we have to convert it to
    fun main
    and add
    runBlocking
    ?
    g
    • 2
    • 2
  • a

    Ahmed Ibrahim

    09/11/2020, 12:50 PM
    Is this the best way to cancel a Deferred? Or is there a better way without the need to access the current `CoroutineContext`'s
    Job
    ?
    suspend <T> fun executeQuery(query: T) {
       val deferred = client.queryCall(query).toDeferred()
    
     currentCoroutineContext()[Job]?.invokeOnCompletion {
           if (it is CancellationException) {
              deferred.cancel(it)
           }
       }
       deferred.await()
    }
    s
    g
    • 3
    • 16
  • v

    voben

    09/11/2020, 3:32 PM
    I would like to send an event where the receiver may not be immediately listening for the event, but when it does, I would like that event to get sent to the receiver. I assumed I could use a Broadcast channel with a capacity of 1 and using the
    send
    suspend function would suspend the coroutine until receiver started listening but that doesn’t seem to be the case. Can anyone provide some input on how to make this work? Sender class
    private val _myEvents = BroadcastChannel<String>(1)
    val myEvents = _viewEvents.asFlow()
    
    ...
    fun doSomething() {
       _myEvents.send("sample string")
    }
    c
    s
    +2
    • 5
    • 22
  • r

    Rita Curado

    09/11/2020, 5:25 PM
    Hi everyone, what is the dependency that I should use on Kotlin Multiplatform iosMain for coroutines? (compliant with the new 1.4.0 Kotlin version) I am getting this error:
    Could not find org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.3.9.
    s
    l
    • 3
    • 8
  • a

    asad.awadia

    09/11/2020, 6:35 PM
    @elizarov is it possible to use flows as a solution to back-pressure across multiple processes? [replicating data over TCP from process A to process B - trying to deal with process A not sending so much that process B can not keep updating its local state] Or should I use something different?
    e
    o
    • 3
    • 4
  • b

    Brendan Weinstein

    09/13/2020, 5:19 AM
    @elizarov Is there a plan for native/iOS multi-threaded coroutines to support a dispatcher backed by more than 2 threads? If so, what's the super rough timeline? Would be great to be able to fully utilize the CPU.
    l
    e
    • 3
    • 2
  • s

    Shashank

    09/13/2020, 5:57 PM
    Hey everyone! I am trying to test my 
    StateFlow
     by asserting the list of values received by it.
    data class State(val isLoading: Boolean, val name: String?)
    
    fun main() {
        val mutableStateFlow = MutableStateFlow(State(false, null))
        val stateFlow = mutableStateFlow as StateFlow<State>
    
        val scope1 = CoroutineScope(Job())
        val scope2 = CoroutineScope(Job())
    
        scope1.launch {
            delay(1000)
            mutableStateFlow.value = State(true, null)
            mutableStateFlow.value = State(false, "name")
        }
    
        scope2.launch {
            stateFlow.collect {
                println("value = $it")
            }
        }
        Thread.sleep(2000)
    }
    Here is my code. Instead of getting 
    State(true, null)
     as the second value, I only receive the initial value and the last value (
    State(false, name)
    )
    a
    z
    +2
    • 5
    • 15
  • s

    spierce7

    09/13/2020, 8:34 PM
    Is converting a
    Flow
    to an
    Observable
    safe? The reason I’m wondering is because the
    Observable
    can be cancelled, but the
    Flow
    can’t. Is the suspending behavior of the coroutine sufficient? With Kotlin Multiplatform for the JS side we’re converting `Flow`s to
    rxjs
    Observable
    s. Code inside the thread.
    l
    z
    e
    • 4
    • 9
  • g

    groostav

    09/14/2020, 8:59 PM
    So I've got a bad idea: What if we embedded a progress bar control and a delegating
    CoroutineDispatcher
    into a coroutineContext such that we could ~automagically make progress bars based on the number of suspension points? I think this is akin to reflecting on the number of states the coroutine state machine has. Of course, while-loops and if-statements blow this up, but still I feel like there might be something here. Has anybody got an implementation doing something like this?
    e
    g
    • 3
    • 13
  • r

    Ricardo C.

    09/15/2020, 9:50 AM
    I’ve been trying to wrap a library that needs to have an initialize method called. This method takes a callback and calls that callback when an object is ready. Now I also want to expose suspend methods that internally use the object that the callback receives. So these suspend methods should suspend waiting for the object until we can then execute normally. I’m not sure how can I suspend waiting for the object in a class-wide scope, as initialize will only be called once at init block. Any ideas? Thanks!
    j
    • 2
    • 12
  • s

    Sudhir Singh Khanger

    09/15/2020, 10:45 AM
    Which Coroutine scope do I use in an Android MVVM Repository? I want to execute a Retrofit call when the repository is created and store its result in a MutableLiveData object within it. That way as long as the repository is not destroyed the use could navigate to the screen and the data would be available. It won't be downloaded over and over if I were to call the retrofit call in the viewModelScope.
    g
    f
    r
    • 4
    • 7
  • d

    Daniele Segato

    09/15/2020, 1:13 PM
    Is there a way to use
    shareIn
    /
    stateIn
    before it is released? Do i need to use a
    -SNAPSHOT
    dependency? Which one? thanks.
    👍 5
    t
    • 2
    • 1
  • p

    Pritam Kadam

    09/16/2020, 12:13 PM
    Hi, I have a question about performing CPU bound operations Should I be using
    Dispatchers.Default
    or create separate scope with fixed thread pools equal to number of cores? what are the pros and cons? what are the criteria's to choose between one of this approach? for ex. Library writer, App writer etc. I have posted detailed explanation and my use cases here https://stackoverflow.com/questions/63915078/can-i-use-dispatchers-default-for-blocking-cpu-bound-operations
    l
    r
    • 3
    • 54
  • s

    spierce7

    09/16/2020, 6:15 PM
    Does kotlinx.coroutines require a new version for 1.4.10? 1.4.10 seems to be released, but I haven’t seen any announcement or anything.
    l
    • 2
    • 1
  • d

    Davide Giuseppe Farella

    09/17/2020, 7:34 AM
    Hello, I got a
    Flow
    like
    flow {
        while (true) {
            emit(something)
            delay(interval)
        }
    }.flowOn(injectedDispatcher)
    In my test, I inject the dispatcher and test like
    val result = mutableListOf<Int>()
    val interval = 30.seconds
    val flow = getSavedCredentials(interval)
    val job = launch {
        flow.toList(result)
    }
    
    repo.add(1)
    advanceTimeBy(interval)
    
    repo.add(2)
    advanceTimeBy(interval)
    
    repo.add(3)
    advanceTimeBy(interval)
    So I would expect
    result
    to be
    [ 1 ], [ 1, 2 ], [ 1, 2, 3 ]
    But instead it is
    [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ]
    What’s wrong with it? 😵
    g
    • 2
    • 20
  • d

    David W

    09/17/2020, 4:27 PM
    Am I correct in thinking that
    launch {
      singletonReceiveChannel.consumeEach { printLine(it) }
    }
    will produce a memory leak due to
    consumeEach
    never getting canceled, even if `launch`'s CoroutineScope ends?
    z
    b
    • 3
    • 6
  • s

    Se7eN

    09/17/2020, 6:56 PM
    This may sound stupid but believe me when I do
    users.postValue(repository.getUsers(20))
    , the getUsers function executes but the value isn't posted but when I do
    list = repository.getUsers(20)
    and then do
    users.postValue(list)
    it works totally fine. What's the deal here?
    i
    • 2
    • 6
  • d

    Daniele Segato

    09/18/2020, 4:24 PM
    How would you write a suspend function to share the result of a function between parallel requests? Let me explain with pseudo-code
    private var shared: Deferred<Result>? = null
    
    private suspend fun actuallyGrabResult(): Result { ... }
    
    suspend fun grabResult(): Result {
      val deferred = shared.takeUnless( !shared.isActive }
        ?: async { actuallyGrabResult() }
            .also { shared = it }
      return deferred.await()
    }
    The idea is that only 1
    actuallyGrabResult()
    coroutine at a given time should be running and any request to
    grabResult()
    should wait for it and get the result. Until the result is delivered, next requests will cause another call. With RxJava you'd do something like:
    private val shared: Single<Result> = actuallyGrabResult()
            .toObservable()
            .replay(1)
            .refCount()
            .singleOrError()
    
    private fun actuallyGrabResult(): Single<Result> { ... }
    
    fun grabResult(): Single<Result> {
      return shared
    }
    Is there an idiomatic way of doing this with coroutine? (I've only recently started using coroutines)
    z
    s
    • 3
    • 14
  • i

    itnoles

    09/18/2020, 5:55 PM
    I found a code from Ktor has
    (dispatcher as Closeable).close()
    inside of
    GlobalScope.launch(super.coroutineContext, start = CoroutineStart.ATOMIC)
    Intellij IDEA reported it as inappropriate blocking method calls. How I can fix it?
    z
    g
    • 3
    • 3
  • n

    Nikita Khlebushkin

    09/18/2020, 11:19 PM
    Hello! What is the status of coroutines multithreading on KMP? I’ve heard that it is not supported atm, but probably it was changed in 1.4?
    s
    • 2
    • 3
  • m

    Mikael Alfredsson

    09/19/2020, 4:27 PM
    I have a small problem when converting a callback to a suspend function. Im trying to wait for a field to be created on a document (firestore) and when the field is created, return the data and continue execution. It works, but since the document listener still is active, Ill get an exception on the next change of the document (alreadyResumedError)
    suspend fun waitForField(id: String): DocModel? = suspendCancellableCoroutine {
        val listener = db.collection("collection").document(id)
            .addSnapshotListener { snapshot, e ->
                if (snapshot == null) return@addSnapshotListener
                val res = snapshot.toObject(DocModel::class.java)
                if (res?.calculation != null) {
                    // here i have to disconnect the listener
                    it.resume(res)
                }
            }
    
        it.invokeOnCancellation {
            listener.remove()
        }
    }
    d
    r
    • 3
    • 9
  • k

    kevinherron

    09/21/2020, 1:54 PM
    Did something change with the “Inappropriate blocking method call” inspection? I’m see it in places like this now:
    val serverModel = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                clientAssociation.retrieveModel()
            }
    where
    retrieveModel()
    throws
    IOException
    . Is this not an appropriate use of
    <http://Dispatchers.IO|Dispatchers.IO>
    ?
    • 1
    • 2
  • s

    spierce7

    09/22/2020, 1:32 AM
    I believe at one point there was a way to create a dispatcher or a context that borrowed threads from another dispatcher, but also ensured that only one thread was accessing the coroutine at a time. Was that ever implemented?
    z
    b
    j
    • 4
    • 20
  • a

    Anders Sveen

    09/22/2020, 7:14 AM
    We love how #ktor works, but are really missing some insights into queuing/delays for co-routines. Would really love to have a way to collect metrics for those things. Right now we suspect it's getting backed up by some slow requests, but hard to diagnose exactly in production. Anyone know of a temporary way to do that while we wait for this issue? https://github.com/Kotlin/kotlinx.coroutines/issues/1360
    l
    • 2
    • 1
  • b

    bsimmons

    09/22/2020, 5:29 PM
    Hey all, so I've just started using 1.3.9-native-mt on iOS/native and I'm getting concurrency/freezing exceptions on code that would otherwise run correctly on the JVM. Is there a simple way to fix this code? Can I just force everything to run on the main thread?
    l
    • 2
    • 4
  • c

    Colton Idle

    09/23/2020, 2:24 AM
    I see here https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core that there's such thing as 1.3.9 and 1.3.9-native-mt I only need regular old coroutines. What's 1.3.9-native-mt?
    g
    • 2
    • 5
  • b

    bbaldino

    09/23/2020, 5:13 PM
    I've got an app that only uses coroutines in one spot (where I'm using ktor) and I want to fire-and-forget a set of requests (I don't want to block the caller on the responses, I just log when responses are received or when they time out). I have an existing IO thread pool for tasks like this. I was originally doing (simplified):
    fun my update() = runBlocking {
        subscribers.forEach { url -> 
            launch(myIoPool.asCoroutineDispatcher()) {
                try {
                    val resp = client.postJson(...)
                    <http://logger.info|logger.info>("Got response...")
                } catch (e: HttpRequestTimeoutException) {
                    logger.error("Timed out...")
                }            
            }
    }
    But I've now realized this is blocking until all the calls to
    launch
    finish. What's the best way to fire-and-forget here? I think I've seen I can do this with
    GlobalScope.launch
    (and getting rid of the
    runBlocking
    ), but from what I've read it seems like it's rarely a good idea to use that.
    a
    g
    • 3
    • 12
  • g

    Glen

    09/24/2020, 1:12 PM
    Hello everyone. A friend asked me if it is possible to build a library, based on coroutines, that interops with native code, targeted for Android. Please, any ideas?(or whether it is possible)
    l
    g
    • 3
    • 42
Powered by Linen
Title
g

Glen

09/24/2020, 1:12 PM
Hello everyone. A friend asked me if it is possible to build a library, based on coroutines, that interops with native code, targeted for Android. Please, any ideas?(or whether it is possible)
l

louiscad

09/24/2020, 2:27 PM
If native code is code using the Android SDK (not the NDK), then sure, people have been doing it since 2017 with success.
g

Glen

09/24/2020, 2:49 PM
Please, @louiscad, can you give me some examples of such libraries?
When I say native code, I mean C code... Targeting Android.
l

louiscad

09/24/2020, 2:55 PM
So NDK… Then you'll need to do the callbacks wrapping and cancellation handling yourself…
g

Glen

09/24/2020, 3:00 PM
OK I see... Thanks for the info👍
I was just wondering if there were any libraries that are carrying out something similar, @louiscad.
l

louiscad

09/24/2020, 3:07 PM
Not that I'm aware of
g

Glen

09/24/2020, 3:10 PM
OK...
l

louiscad

09/24/2020, 3:11 PM
Now, Android Studio recent versions added autocompletion for JNI interop in Kotlin/C, so that might be helpful
g

Glen

09/24/2020, 3:23 PM
OK. Noted. So I will have to write wrappers for coroutines in the form if callbacks...Serious lot of work...
Thanks for your help, @louiscad.
I wanted to use IntelliJ IDEA to create the library...
l

louiscad

09/24/2020, 3:43 PM
Android Studio is free and is almost the same.
g

gildor

09/25/2020, 5:42 AM
So I will have to write wrappers for coroutines in the form if callbacks...Serious lot of work...
Some C++ Future/Promice class can be exposed instead of callback, so it would be enough to write one single await() function for it, so it will be universal for all async calls to native code But in general it really depends what kind C code you try to integrate
I doubt that there is any library, there are too many different C APIs, and no single= abstraction for async operations
g

Glen

09/25/2020, 8:47 AM
But is it possible that I use Kotlin/Native and generate a library that I can then consume on the Android side?
Any thoughts, @louiscad or @andreasmattsson?
l

louiscad

09/25/2020, 8:57 AM
Yes, but there's no java-like interop between Kotlin/Native and Kotlin/JVM, so you'll need glue code/an adapter. Also, kotlinx.coroutines is not available on the Android NDK (https://github.com/Kotlin/kotlinx.coroutines/issues/812), so you'll need to compile it yourself.
g

gildor

09/25/2020, 9:11 AM
I really don’t think that you need Kotlin/Native if your final goal is to use some C API on Android/JVM, K/N is just one more layer which doesn’t improve anything Better to have JNI directly to C API from JVM (or any of options which generates JNI glue for you) And on top of this Java JNI API you can add coroutines
g

Glen

09/25/2020, 9:16 AM
Thanks @gildor. But I have two questions. The first is, why can't I use K/N to avoid JNI altogether? and, How can I add coroutines on top of the JNI API?, because my goal is to use coroutines natively.
But from what @louiscad said above, it seems that it is not possible for the moment.
g

gildor

09/25/2020, 9:39 AM
The first is, why can’t I use K/N to avoid JNI altogether
You can, but then you have to write JNI to talk with K/N from Android It maybe a viable option if most of loigic on k/n side and you have simple interaction with it
How can I add coroutines on top of the JNI API?,
JNI api is just Java (or Kotlin JVM) code, no issue to write coroutines adapter on top of it
g

Glen

09/25/2020, 9:51 AM
I am working on an image processing library, where most of the specific image processing code is already written in C. I want to use coroutines when calling specific functions from the C API, then generate the code I have written into library that I can then use on the Android side.
With all of this, is K/N still a viable option, @gildor?
g

gildor

09/25/2020, 10:01 AM
I don’t think so honestly
if most of code already written in C
why not just “specific functions from the C API” do in JNI and wrap those JNI calls to coroutines
g

Glen

09/25/2020, 10:04 AM
Yeah, seems like a more pragmatic solution.
I wanted to create Kotlin bindings for the C code, generate a KLib, and use that on the Android side, @gildor.
g

gildor

09/25/2020, 10:10 AM
if Android wouldn’t be involved, if fine solution, but writing one more layer of bindings on top of it looks as not the best idea
I would like to have direct interop from JVM to C using the same cinterop mechanism + jni, but there is no such thing (though, K/N itself uses something similar under the hood, because compiler is JVM program)
g

Glen

09/25/2020, 10:14 AM
Yeah... Thanks a lot for your help, @louiscad, and @gildor. I really appreciate it. 🙏
I will just write a bunch of
external fun
methods and wrap them with coroutines.
g

gildor

09/25/2020, 10:24 AM
you also can use something like JNA to wrap C API without writing all glue manually
g

Glen

09/25/2020, 10:27 AM
Please @gildor, do you have any links or hints on how to achieve that? It will be of great help.
g

gildor

09/25/2020, 10:56 AM
I meant that you can use something like JNA https://github.com/java-native-access/jna or similar approaches to generate jni
g

Glen

09/25/2020, 11:00 AM
Ok. Thanks very much...🙏
But @gildor,I can use JNA directly with Kotlin, right?
g

gildor

09/25/2020, 2:30 PM
Yeah, JNA works with standard interfaes, shouldn't be an issue
g

Glen

09/26/2020, 12:50 PM
Thanks very much🙏
Hi there. I found this interesting library . Maybe I could use it as an alternative...🤷‍♂️
View count: 6