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

    Dominaezzz

    02/08/2019, 11:02 PM
    How to specify Kotlin/Native stdlib as dependency in "commonNative" sourceSet?
    d
    7 replies · 2 participants
  • j

    juancho

    02/10/2019, 2:35 PM
    Hi all, not sure if this was the right channel to ask this. I created a Multiplatform project with Kotlin 1.3.20, a Native target for iOS and using Kotlinx.serialization 0.10.0. I could successfully create the Framework and use it in iOS but in order to make it work in iOS I exported the native serialization runtime library to be included in the framework like this:
    iosX64("ios") {
        compilations.main.outputKinds("framework")
        binaries {
            framework {
                export "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:0.10.0"
            }
        }
    }
    My question: Is there any way that I can avoid doing this and add this dependency in the iOS project? (using the kotlinx repository which is bintray right now) I’m asking this as I would like to start creating more Frameworks that depends on this serialization runtime but I don’t want to include it in every framework, specially if those frameworks are going to be used in the same iOS project.
    r
    s
    +1
    17 replies · 4 participants
  • j

    jmullin

    02/10/2019, 7:06 PM
    @svyatoslav.scherbina I wonder if your above commit represents some hope that restriction is going away, or has been removed? 😃
    s
    g
    +2
    10 replies · 5 participants
  • j

    JoakimForslund

    02/11/2019, 8:26 AM
    Hopefully an easy question, how do you name the dynamic/static output of a kotlin library from
    main
    to something else from the build script? Im guessing there is something better than rename the output files afterwards?
    j
    j
    9 replies · 3 participants
  • n

    Nico Buescher

    02/12/2019, 1:36 AM
    Hey all. So I'm a little confused about c strings in relation to struct members. If I have a c struct defined as such:
    typedef struct {
        const char *str;
    } Example;
    What is the intended way to store a string literal in
    str
    from Kotlin? Using
    "String".cstr
    doesn't work since
    str
    is a
    CPointer<ByteVar>
    , and
    String.cstr
    is a
    CValues<ByteVar>
    , and when I use
    memScoped { ... }
    with
    getPointer(memScope)
    , the CString is obviously freed as soon as the scope is finished, leaving me with an empty string in the struct member.
    d
    o
    8 replies · 3 participants
  • r

    Roman

    02/12/2019, 9:26 AM
    Good time of day. This is not a working moment, but interest has appeared.Is it possible to do “assembly inserts” in “kotlin native”?
    s
    g
    +2
    6 replies · 5 participants
  • m

    marchuck

    02/12/2019, 10:34 AM
    hi there https://kotlinlang.org/docs/reference/native/objc_interop.html doc says Unit should be mapped into Void in Swift but when I am using closures in kotlin like
    (String)-> Unit
    it messes in Swift files into
    KotlinUnit
    object. Can I deal with this in more elegant way?
    g
    j
    2 replies · 3 participants
  • c

    conner

    02/12/2019, 3:06 PM
    has anyone done any work with using protos for interop between KN and objective-c? is there any working way to pass protos to kotlin native? kotlinx.serialization looks close, but wouldn't that require that all clients convert to bytes first?
    o
    n
    3 replies · 3 participants
  • r

    Roman

    02/13/2019, 3:54 AM
    Hi, I decided to try assembly inserts in KN. As suggested, it is possible to write them in
    def
    . Great, I found examples of usage http://asmcourse.cs.msu.ru/wp-content/uploads/2013/04/gcc-inline-asm.pdf https://ru.stackoverflow.com/questions/829868/%D0%90%D1%81%D1%81%D0%B5%D0%BC%D0%B1%D0%BB%D0%B5%D1%80%D0%BD%D0%B0%D1%8F-%D0%B2%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0-%D0%B2-%D0%A1%D0%B8 but an error crashes: <inline asm>2️⃣11: error: unknown token in expression mov eax, %ecx ^ <inline asm>3️⃣11: error: unknown token in expression add eax, %edx ^ <inline asm>4️⃣6: error: unknown token in expression mov %ecx, eax ^ LLVM ERROR: Error parsing inline asm Prompt is a mistake in the syntax or you still can not do so. This is the
    def
    file itself: --- #include <windows.h> #include <stdio.h> #include <tchar.h> int prin() { int a = 1; int b = 2; int c; __asm(".intel_syntax noprefix\n\t" // директива GAS, включаем Intel синтаксис. "mov eax, %1\n\t" // перемещаем в eax значение переменной a. "add eax, %2\n\t" // прибавляем значение переменной b к eax. "mov %0, eax\n\t" // перемещаем в переменную c значение eax. :"=r"(c) // список выходных параметров. :"r"(a), "r"(b) // список входных параметров. : "eax" // список разрушаемых регистров. ); printf("%d + %d = %d\n", a, b, c); return 0; }
    o
    s
    3 replies · 3 participants
  • i

    ivan.savytskyi

    02/13/2019, 5:27 PM
    hey folks question regarding implementation of Ktor http client on iOS https://github.com/ktorio/ktor/blob/master/ktor-client/ktor-client-ios/darwin/src/io/ktor/client/engine/ios/IosClientEngine.kt#L22 and https://github.com/ktorio/ktor/blob/master/ktor-client/ktor-client-ios/darwin/src/io/ktor/client/engine/ios/IosClientEngine.kt#L76 After looking at the source code, am I right that the deserialization of raw bytes (for example via kotlinx.serialization) will be done on the main thread?
    s
    4 replies · 2 participants
  • b

    bob

    02/13/2019, 7:21 PM
    Which is the easiest way to provide a GUI (windowed) applications for Mac & Windows?
    d
    1 reply · 2 participants
  • s

    spierce7

    02/13/2019, 11:29 PM
    What kotlin platform compilers currently have an IR?
    g
    s
    2 replies · 3 participants
  • r

    Roman

    02/14/2019, 11:47 AM
    How can I change a global variable from another thread. I tried "@ kotlin.native.SharedImmutable" but this led to the error: "IncorrectDereferenceException: Trying to get it out of the non-main thread "
    Kt.txt
    d
    s
    26 replies · 3 participants
  • s

    safa

    02/14/2019, 12:31 PM
    Hello, a Kotlin/Native question: is it possible to have a shared
    .so
    KN runtime? Under the hood, I see program.bc runtime.bc and hello.bc being combined and linked. Our project needs to generate a lot of shared libs for interop and runtime loading, and it quickly grows in size considering the same stuff being put into all of them. Ideally I'd look into generating a shared runtime and lightweight libraries that are dynamically linked to that. @olonho @svyatoslav.scherbina @jb.igor.chevdar thanks
    o
    l
    2 replies · 3 participants
  • a

    ahmedre

    02/14/2019, 1:54 PM
    Hi, I have a question - I have a project using the kotlin-multiplatform plugin consisting of multiple modules. I am able to get everything compiling (and get a jar and klib for each module). I am trying to figure out how to get a single iOS framework built from the combination of all these klibs. I was trying to create a separate gradle module that depends on all the aforementioned modules and set:
    fromPreset(presets.iosX64, 'ios') {
                compilations.main.outputKinds('FRAMEWORK')
            }
    in order to get one framework, but I notice that: 1. I have to have code within this module in order for it to build a framework 2. the framework doesn’t include the dependencies I’ve tried also adding the set of dependencies explicitly under
    iosMain
    (with
    api
    instead of
    implementation
    and the
    implementation
    counterparts in
    commonMain
    ), and tried adding a block with:
    iosX64("ios").binaries {
            framework {
                export project(":one")
                export project(':two')
                export project(":three")
    
                transitiveExport = true
            }
        }
    but the framework i am getting only has the files from this specific module without the dependencies. if i explicitly reference a class from one of these dependent modules, the header file that is generated grows, but i want a way to include them without manually referencing something from each module. may someone point me to the right direction on how to combine the klibs from these multiple modules into one single iOS framework?
    s
    7 replies · 2 participants
  • k

    kpgalligan

    02/14/2019, 3:33 PM
    Kind of missed the memo on this. “Kotlin/Native will embed bitcode by default for iOS frameworks targets in Gradle projects.” Is that regular llvm bitcode, or the Apple-specific “bitcode” required for watch and some other builds?
    s
    r
    +1
    27 replies · 4 participants
  • s

    Slackbot

    02/14/2019, 3:55 PM
    This message was deleted.
    s
    r
    2 replies · 3 participants
  • d

    Diego

    02/14/2019, 4:59 PM
    Hello guys. I’m using Kotlin 1.3.20 and gradle 5.1 (along with serialization 0.10.0) in a MPP (Android & iOS). I need to import a custom framework (aka MyUtils) but when I run
    ./gradlew clean build
    I got the following error:
    > Task :common:linkTestDebugExecutableIOS
    ld: framework not found MyUtils
    error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld invocation reported errors
    Here is the iOS part of my
    build.gradle
    file:
    kotlin {
        targets {
            fromPreset(presets.iosArm32, 'iOS') {
                def frameworksDir = "${projectDir}/Frameworks"
                
                binaries {
                    framework("p2p_common") {
                        linkerOpts "-F${frameworksDir}"
                    }
                }
                compilations.main.extraOpts '-Xembed-bitcode-marker'
                compilations.main.cinterops {
                    MyUtils {
                        defFile "src/iOSMain/c_interop/MyUtilsFramework.def"
                        packageName "com.acme.utils"
                        includeDirs "${frameworksDir}/MyUtils.framework/Headers"
                    }
                }
            }
            fromPreset(presets.android, 'android')
        }
    	...
    MyUtilsFramework.def
    language = Objective-C
    headers = MyUtils-Swift.h
    compilerOpts = -framework MyUtils
    linkerOpts = -framework MyUtils
    excludeDependentModules = true
    I can see the
    p2p-common-cinterop-MyUtils.klib
    is generated and actually I can see the classes of the framework from the kotlin code inside the folder
    iOSMain
    but as I said before the build fails. Has anyone a clue why this happens and how I can fix this problem?
    d
    4 replies · 2 participants
  • n

    Nathan

    02/14/2019, 7:53 PM
    anyone know when native will be updated to work with gradle 5+?
    l
    g
    +2
    16 replies · 5 participants
  • d

    Diego

    02/15/2019, 5:02 PM
    Hello guys. I have a pure Swift framework that I want to use from a Kotlin MPP. In order to be able to use the framework I had to create [this bridging class](https://gist.github.com/dfpalomar/0322a839ba2bd4b5959be3ca9d58c3eb#file-cryptobridge-swift) and annotate the class and methods with
    @objc
    . I updated my build.gradle file to add the
    cinterops
    configuration and the problem is that when I try to build the project I get the following error:
    > Task :p2p-common:cinteropCryptoCocoaIOS FAILED
    Exception in thread "main" java.lang.Error: CryptoCocoa.framework/Headers/CryptoCocoa-Swift.h:203:4: error: expected a type
    [
    CryptoCocoa-Swift.h
    ](https://gist.github.com/dfpalomar/0322a839ba2bd4b5959be3ca9d58c3eb#gistcomment-2837982) is a file generated by Xcode. The line 203 is
    - (NSData * _Nonnull)generateAESKeyWithKeySize:(NSInteger)keySize SWIFT_WARN_UNUSED_RESULT;
    Am I using an unsupported swift feature? Any idea about how can I sort this out?
    s
    2 replies · 2 participants
  • c

    conner

    02/15/2019, 8:24 PM
    hi! the docs (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/members.html) say
    KClass.members
    is available on native, but https://github.com/JetBrains/kotlin-native/blob/master/runtime/src/main/kotlin/kotlin/reflect/KClass.kt seems to suggest otherwise (and I cannot compile). Is this a mismatch in documentation, or am I somehow using it incorrectly? I'm using gradle with kotlin 1.3.21
    o
    1 reply · 2 participants
  • l

    Landerl Young

    02/16/2019, 4:46 AM
    I’m trying to write a simple code shrink phase to K/N compiler, but met servral problems. Could someone give me some help. I planed to do a
    Markup Sweep
    algorithm to detect dead code. But I found that the shrink phase must be operated on bit code instead of IR in order to shrink library code. However the bitcode contains much more data than simply class and methods (lke java byte code), which makes the shrink phase much hard. Especially the TypeInfo, OC export, CStubs, etc... That makes Class/Function removal more hard. And also, it seems impossible to remove virtual methods, since which would change the vtable structure, and make the existing method index invalid. I’m new to K/N compiler (but experienced on K/N itself), the compiler do steps like SourceCode -> PSI -> IR -> bitcode. I’m curiousied that what is the IR. Is it LLVM-IR, or just a Jetbrain defined IR shared with Kotlin/JVM? To sum up, my questions is: 1. How to deal with OCExport,CStubs etc, when a Class/Function is removed. 2. How to remove virtual methods. 3. What is the DFG? 4. To shrink bitcode, can I take advantage of DFG or IR in the
    Context
    ?
    o
    8 replies · 2 participants
  • g

    GarouDan

    02/16/2019, 11:51 PM
    Hi, have someone being able to create docker containers to build iOS/macOS or Windows applications? I'll really appreciate a dockerfile... 😆
    s
    m
    +1
    15 replies · 4 participants
  • j

    juancho

    02/17/2019, 3:12 PM
    Hello guys, I created a custom exception in Kotlin Native and I was able to capture the exception in the iOS platform but I’m not able to access the custom properties of my exception. Is there any way to do that? Native Custom Exception:
    class MyException(
        val myCustomProp: Boolean
    ): Throwable()
    in iOS with Swift:
    } catch let error as MyException {
          print("custom value: \(error.myCustomProp)")
    } catch let error {
          print(error.localizedDescription)
    }
    but it always go to the latest catch
    d
    o
    9 replies · 3 participants
  • a

    Alexander Suslov

    02/18/2019, 9:58 AM
    Hi all! Could you please explain me how to use the
    @ThreadLocal
    annotation? I have a code:
    ...
    object FooObject {
    
    	@ThreadLocal
    	var bar: String = "first"
    }
    
    fun testObj() {
    	val before = FooObject.bar
    	println("before = $before")
    
    	FooObject.bar = "second"
    
    	val after = FooObject.bar
    	println("after = $after")
    }
    ...
    But when I run it, I receive a error:
    before = first
    Instances of kotlin.Error, kotlin.RuntimeException and subclasses aren't propagated from Kotlin to Objective-C/Swift.
    Other exceptions can be propagated as NSError if method has or inherits @Throws annotation.
    Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen org.kotlin.mpp.mobile.FooObject@398928
            at 0   CoreModule                          0x000000010bd9ff36 kfun:kotlin.Exception.<init>(kotlin.String?)kotlin.Exception + 70
            at 1   CoreModule                          0x000000010bd9fea6 kfun:kotlin.RuntimeException.<init>(kotlin.String?)kotlin.RuntimeException + 70
            at 2   CoreModule                          0x000000010bda17a6 kfun:kotlin.native.concurrent.InvalidMutabilityException.<init>(kotlin.String)kotlin.native.concurrent.InvalidMutabilityException + 70
            at 3   CoreModule                          0x000000010bdc6da3 ThrowInvalidMutabilityException + 275
            at 4   CoreModule                          0x000000010bde18f2 MutationCheck + 50
            at 5   CoreModule                          0x000000010bd97c63 kfun:org.kotlin.mpp.mobile.FooObject.<set-bar>(kotlin.String) + 67
            at 6   CoreModule                          0x000000010bd9ed56 kfun:org.kotlin.mpp.mobile.testObj() + 342
            at 7   CoreModule                          0x000000010bd9eb2e kfun:org.kotlin.mpp.mobile.platformName()kotlin.String + 62
            at 8   CoreModule                          0x000000010bd9ea82 
    ...
    Why the
    bar
    variable is frozen in this case?
    y
    5 replies · 2 participants
  • y

    yusuf3000

    02/18/2019, 2:33 PM
    Could someone help me as to why when I build an
    iosArm64
    klib it can’t find the corresponding
    actual
    class for an
    expect
    class but it works fine when building an
    iosX64
    klib?
    s
    4 replies · 2 participants
  • t

    tapchicoma

    02/20/2019, 8:32 AM
    Hi, any plans for resolving this issue: https://github.com/JetBrains/kotlin-native/issues/2440 Or old native plugin is deprecated and will not receive updates?
    o
    2 replies · 2 participants
  • g

    GarouDan

    02/20/2019, 2:43 PM
    Hi guys, do you know the latest supported version of gradle that I can use with kotlin native? I’m trying with 5.2.1 but I’m receiving the following errors:
    The IvyArtifactRepository.layout(String, Action) method has been deprecated. This is scheduled to be removed in Gradle 6.0. Please use the IvyArtifactRepository.patternLayout(Action) method instead.
    Could not create an instance of type org.jetbrains.kotlin.gradle.dsl.KotlinNativeBinaryContainer.
    > org.gradle.util.WrapUtil.toNamedDomainObjectSet(Ljava/lang/Class;[Lorg/gradle/api/Named;)Lorg/gradle/api/NamedDomainObjectSet;
    This is related with the last message, but for now I would like to try to latest supported version of gradle too.
    n
    2 replies · 2 participants
  • b

    basher

    02/21/2019, 1:53 AM
    Does anyone have an example of getting a pointer to a local
    Int
    (or other primitive) without using
    alloc
    in
    memScoped
    ? I'm trying to do it useing
    usePinned
    , but i'm having trouble navigating the types. Is the the right direction?
    d
    o
    +3
    14 replies · 6 participants
  • i

    ivan.savytskyi

    02/21/2019, 2:52 AM
    hey folks I found several ways how to deliver the result of background task execution back to the main thread on iOS, one example shown in
    DroidconKotlin
    by Touchlab https://github.com/touchlab/DroidconKotlin/blob/kotlin-1.3.20/sessionize/lib/src/iosMain/kotlin/co/touchlab/sessionize/platform/Functions.kt#L49 it uses ThreadLocal wrapper. The question why not just do this instead:
    override operator fun <T> invoke(query: Database.() -> T, callback: (T) -> Unit) {
            worker.execute(TransferMode.SAFE, { QueryTask(database, query, callback).freeze() }) { task ->
                val result = task.query(task.database)
                dispatch_async_f(
                    queue = dispatch_get_main_queue(),
                    context = DetachedObjectGraph { QueryTaskResult(result.freeze(), task.callback) }.asCPointer(),
                    work = staticCFunction { it: COpaquePointer? ->
                        initRuntimeIfNeeded()
                        val result = DetachedObjectGraph<Any>(it).attach() as QueryTaskResult<T>
                        result.callback(result.result)
                    }
                )
            }
        }
    Am I missing something, and there is something wrong with the code above? It seems working
    y
    o
    +1
    14 replies · 4 participants
Powered by Linen
Title
i

ivan.savytskyi

02/21/2019, 2:52 AM
hey folks I found several ways how to deliver the result of background task execution back to the main thread on iOS, one example shown in
DroidconKotlin
by Touchlab https://github.com/touchlab/DroidconKotlin/blob/kotlin-1.3.20/sessionize/lib/src/iosMain/kotlin/co/touchlab/sessionize/platform/Functions.kt#L49 it uses ThreadLocal wrapper. The question why not just do this instead:
override operator fun <T> invoke(query: Database.() -> T, callback: (T) -> Unit) {
        worker.execute(TransferMode.SAFE, { QueryTask(database, query, callback).freeze() }) { task ->
            val result = task.query(task.database)
            dispatch_async_f(
                queue = dispatch_get_main_queue(),
                context = DetachedObjectGraph { QueryTaskResult(result.freeze(), task.callback) }.asCPointer(),
                work = staticCFunction { it: COpaquePointer? ->
                    initRuntimeIfNeeded()
                    val result = DetachedObjectGraph<Any>(it).attach() as QueryTaskResult<T>
                    result.callback(result.result)
                }
            )
        }
    }
Am I missing something, and there is something wrong with the code above? It seems working
y

yshrsmz

02/21/2019, 3:17 AM
From my understanding, if you freeze callback, everything you reference from inside callback will be frozen.
👀 1
For example you can't use coroutine from callback in your example.
i

ivan.savytskyi

02/21/2019, 4:02 AM
Callback is passed from iOS VC, and inside the callback it renders some UI. So far works just fine.
And the same happens in the sample code from Touchlab,
JobWrapper(backJob, mainJobHolder).freeze()
.
o

olonho

02/21/2019, 5:00 AM
Generally there are few examples around this problem in https://github.com/JetBrains/kotlin-native/blob/master/samples/objc/src/objcMain/kotlin/Async.kt
especially
Continuator
solves problem of non-freezing the callback
y

yshrsmz

02/21/2019, 6:02 AM
Thanks! I'll look into it
In the meantime I wrote some quick test to check the behaviour of ThreadLocalRef. If we wrap lambda with ThreadLocalRef, then that lambda is not frozen https://gist.github.com/yshrsmz/cf9c53bac9b07b3ca02c1286ea796ad1
i

ivan.savytskyi

02/21/2019, 4:30 PM
@olonho thx for the sharing examples. One more question (I’m trying to get my head around how the freeze operation works) I can see how that works for any model object graph, so everything marked to be immutable and raise exception if someone tries to modify it. But what
freeze
operation does for the closure / callback especially if it passed from let’s say swift realm, what implications of freezing passed callback?
o

olonho

02/21/2019, 5:03 PM
Freeze doesn’t go cross-runtime, Swift/C data keeps their mutability
👍 1
k

kpgalligan

02/21/2019, 7:26 PM
I’m just seeing this. Will have to look in detail at the “why not just do ___“, but I wrote the droidcon code. The basic idea is that I want to pass the function to be executed when the background returns to the main thread, and to avoid freezing, that is kept in the thread it is called from and returning to (IE. the main thread). I do the same thing with a generic coroutines background processor (backgroundSuspend) and the sqldelight Pub/Sub listener in the app. The background tasks are generally frozen, but any function/lambda set and called in the main thread is kept local to the thread, and avoids freezing. I have a pending blog post to talk about this, but I have a lot of pending blog posts, and no real eta on that.
I made a video explaining better. Posting when uploaded

https://www.youtube.com/watch?v=yhvsKlxPZPQ&amp;feature=youtu.be▾

👏 2
i

ivan.savytskyi

02/25/2019, 5:45 PM
thx @kpgalligan!!!
View count: 4