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
javascript
  • m

    Marc Knaup

    12/04/2020, 3:40 PM
    Is there any way to initialize file-scoped variables lazily just like on JVM without adding
    lazy
    & related overhead to every single one of them? In my project I use the pattern
    val foo = object : SomeBaseClass { … }
    quite a lot and just now recognized that there’s an insane amount of initialization going on during startup. All such
    val
    get evaluated at startup and all properties of these objects get evaluated too which in turn runs all their delegate providers.
    s
    s
    • 3
    • 8
  • t

    tarek

    12/06/2020, 11:50 AM
    Hi I am struggling to access test resources from a JS browser test. I see the files alongside the test.js in the build folder. How can I access their content from within the test ? I tried using
    window.fetch
    but I get 404s
    t
    • 2
    • 7
  • t

    tarek

    12/06/2020, 5:10 PM
    Any tips for cleaning up Dukat generated externals? I tried using them for
    @svgdot/svg.js
    but I’m struggling to make them compile Is there any config optios for it? Or should I edit all the externals manually?
    👀 1
    v
    • 2
    • 2
  • t

    Tiago Nunes

    12/06/2020, 9:57 PM
    Hi everyone 🙂 I'm new to Kotlin/JS, and I'm following the docs. I was testing how I could work with jQuery in kotlin. I followed this steps: https://kotlinlang.org/docs/reference/js-external-declarations-with-dukat.html
    implementation(npm("jquery", "3.5.1"))
    implementation(npm("@types/jquery", "3.5.1", generateExternals = true))
    However, I got a bunch of compile errors when running gradlew run, errors like:
    'addEventListener' overrides nothing
    'addEventListener' overrides nothing
    'addEventListener' overrides nothing
    'addEventListener' overrides nothing
    'removeEventListener' overrides nothing
    'removeEventListener' overrides nothing
    Can dukat not yet convert declarations from @types/jquery 3.5.1? How then can I use jQuery in kotlin (with declarations)?
    r
    j
    • 3
    • 13
  • d

    darkmoon_uk

    12/09/2020, 7:52 AM
    Is anyone using Kotlin to generate React Native code - what's your workflow like? Disclaimer: I do not see this as desirable vs. Native Mobile development; just being forced to adopt a React Native project and considering options to start writing in Kotlin in prep for an eventual rewrite, early on.
    👍 1
    n
    • 2
    • 1
  • s

    Sebastian Aigner

    12/09/2020, 12:25 PM
    ❄️ It’s that time of the year again! stateofjs.com is surveying developers to identify current and upcoming trends in the JavaScript ecosystem. This survey has a lot of questions that center around pure JavaScript and its APIs, but also asks about language flavors. ✏️ If you are filling out their survey, please support us by writing in “Kotlin/JS” on the “JavaScript Flavors” page, and give “Kotlin” a tick on “Other Tools | Non-JavaScript Languages”. 📈 Last year, 2.3% of freeform answers already contained “Kotlin” – let’s try to beat it this year! 💪🏼
    :javascript: 8
    :kotlin: 13
    ✅ 5
    r
    a
    b
    • 4
    • 4
  • s

    Sebastian Owodzin

    12/15/2020, 12:49 AM
    Hi! Sorry if this was already asked. I’m upgrading firebase in a multiplatform project that has a JS target. Previous firebase versions that supported
    import * as firebase from 'firebase/app';
    & I could do the following:
    @JsModule("firebase/app")
    external object firebase {
      ...
    }
    But now in their docs it’s
    import firebase from 'firebase/app';
    and I’m getting
    TypeError: $module$firebase_app.initializeApp is not a function
    Anyone have an idea how to properly import this?
    t
    • 2
    • 2
  • t

    TheOnlyTails

    12/16/2020, 5:49 PM
    hi! I started following this guide about Kotlin/JS, yet I'm stuck on this part: https://play.kotlinlang.org/hands-on/Building%20Web%20Applications%20with%20React%20and%20Kotlin%20JS/03_A_First_Static_Page, where you do the
    KotlinConf Explorer
    Page. I made sure my code is right (I checked the repo), yet nothing appears in my browser.
    m
    • 2
    • 10
  • h

    Harald Pehl

    12/17/2020, 8:50 AM
    I'm pleased to announce the first public release of PatternFly Fritz2. PatternFly Fritz2 is a Kotlin/JS implementation of PatternFly based on fritz2. The goal of PatternFly Fritz2 is to provide all PatternFly components in Kotlin/JS. This is done in a way that matches the reactive nature of fritz2. To get a quick overview take a look at the PatternFly Fritz2 showcase. It demonstrates the usage of all available components and and also includes more complex demos of data driven components such as card view, data list and data table. PatternFly Fritz2 is still under development. The API might change and things might not work as expected. Please give it a try and share your feedback.
    🎉 3
    d
    • 2
    • 2
  • b

    Brandon Saunders

    12/17/2020, 10:39 AM
    Question here for the room. We have a project with a main library and a shared library. We recently moved some items from the main library to the shared library and noticed that they were no longer accessible from consumers of the main library. They could still be used within the main library but the JS runtime wasn’t able to reference any of them from their namespaces. Is there a known right workaround for this? For context we’re working in a multiplatform project but I don’t think that should impact this.
    t
    m
    • 3
    • 21
  • a

    Andrey Nikanorov

    12/17/2020, 7:37 PM
    Hi! Please help me with advice, how to investigate this issue. I have project with react and everything runs fine on "debug" webpack run. But I have a strange issue on
    browserProductionWebpack
    . One of the
    setState{}
    is not executed. Without any errors in console. All code before and after
    setState{}
    executed fine, but not inside. How to investigate such issues? Legacy compiler
    r
    • 2
    • 4
  • a

    Alfred Lopez

    12/17/2020, 9:48 PM
    I'm new to Kotlin/JS and I would like some "jumpstart help", which the docs don't provide. I'm trying to iterate through the Node's process.env object. But I really have no idea how to code that in Kotlin. I've put the dotenv npm dependencies in my gradle file and done the external process in my Kotlin file, but not sure how to "manipulate" the object. I know I can do process.env.MY_PROPERTY, but I don't know how address this object to iterate through its keys. Thanks
    r
    • 2
    • 2
  • a

    andylamax

    12/17/2020, 10:28 PM
    Hello, while i can write kotlin/js tests well, I can't however run and see the results in the IDE. It returns with
    FAILURE: Build failed with an exception.
    * What went wrong:
    Could not determine the dependencies of task ':sandbox-react:testPackageJson'.
    > NPM Dependencies already resolved and installed
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    * Get more help at <https://help.gradle.org>
    Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
    Use '--warning-mode all' to show the individual deprecation warnings.
    See <https://docs.gradle.org/6.7.1/userguide/command_line_interface.html#sec:command_line_warnings>
    BUILD FAILED in 1s
    01:26:55: Task execution finished ':sandbox-react:test'.
    How ever, running with gradle successfully executes the test. Is this a known bug? any workaround? IR Backend
    r
    • 2
    • 3
  • t

    thana

    12/18/2020, 10:41 AM
    the other question is: how can i keep function names when the bundle is minified?
    r
    • 2
    • 2
  • t

    thana

    12/18/2020, 11:17 AM
    i tried to modify the webpack config with the documented
    webpack.config.d
    folder, but it doesn seem to have any impact on the resulting
    webpack.config.js
    what is missing if those files are ignored?
    m
    • 2
    • 4
  • t

    thana

    12/18/2020, 12:29 PM
    ok i finally found a solution for my actual problem: the dce step would remove some methods. I first thought the method is simply renamed so i tried to find out how to avoid the method is removed. But as @Robert Jaros pointed out, when using
    @JsName
    the method named isn;t mangled and indeed i can find some emthods from my code with the correct name in the resulting bundle. I thought configuring the terser plugin is the way to go, but didn't work out becasue the config in
    webpack.config.d
    is ignored. But then i found out: its indeed dce that removes the method! i tried
    dceTask{keep{..}}
    but couldn;'t make it work. No i finally figured: the methods removed reside in the default package. So the question is: is it a bug or a feature that you cannot
    keep
    a mthod from the default package?
    m
    • 2
    • 1
  • t

    thana

    12/18/2020, 3:01 PM
    ok, current state to the aforementioned problems: the function thrown out by the terser plugin was named "initialize" which is the root of all evil. the method must not be named so, it must have a different name, then all is fine. this js stuff is so incredibly crappy
    m
    • 2
    • 10
  • t

    TheOnlyTails

    12/19/2020, 12:45 PM
    hi! I'm trying to read a JSON array from a file, store it as a List in my component, and use it to display some stuff, yet I'm getting this error: Warning: Can't call setState on a component that is not yet mounted.Here is my code: The classes to display the list:
    data class Member(val name: String, val githubUrl: String, val positions: List<String>)
        
    external interface MemberListState : RState { 
        var members: List<Member> 
    }  
    
    class MemberList : RComponent<RProps, MemberListState>() {     
        override fun RBuilder.render() {         
            ul {             
                for (member in state.members) {     
                    li {                     
                        styledA {                         
                             css { attrs.href = member.githubUrl }                         
                             +member.name                     
                        }
                    }                      
                    ul {                         
                        member.positions.forEach {         
                            li { +it }                         
                        }
                    }
                }
            }
        }
    
        private fun fetchMembers() = window.fetch("./members.json").unsafeCast<Array<Member>>()
    
        override fun MemberListState.init() {
            val jsonMembers = fetchMembers()
            members = listOf()
    
            setState {
                members = jsonMembers.toList()
            }
        }
    }
    The use of the code:
    class App : RComponent<RProps, RState>() {     
        override fun RBuilder.render() {         
            child(MemberList::class) {}   
        } 
    }
    Thanks in advance!
    a
    h
    • 3
    • 7
  • v

    Vladyslav Sitalo

    12/19/2020, 11:47 PM
    I’m curious if there is a react component library out there with cohesive styling/etc and Kotlin bindings already created for it?
    • 1
    • 1
  • k

    Kirill Garkusha

    12/20/2020, 5:08 PM
    Hi. I am working with multiplatform library (based on 1.4.21) and struck with suspend functions. I can't find any info how to use them from JS. I can see them from JS code, but I get an error when I am calling them.
    Cannot read property context
    I see that method signature in JS has additional param - continuation. How should I use it?
    m
    j
    l
    • 4
    • 5
  • c

    CLOVIS

    12/21/2020, 3:51 PM
    What is the recommended way to unit test suspending code in Kotlin/JS? I've been using https://stackoverflow.com/questions/47956444/how-to-unit-test-kotlin-js-code-with-coroutines for a while, but when there are many tests, some timeout. If I run tests by one, they never timeout, but if I run all of them, 2–3 tests timeout (different ones everytime). I'm starting to think returning a Promise means they all start at the same time, and some have to wait for the others to finish so there are enough threads? What can I do to solve this?
    t
    r
    +2
    • 5
    • 7
  • d

    Daniel Rampelt

    12/21/2020, 9:47 PM
    Does kotlin download/use its own version of node, and if so, is it possible to change that version? I have an npm dependency that requires
    node >= 12.17
    and my build is failing since it seems to be running with
    12.16.1
    . I use nvm on my computer for other node projects, and the only versions I have installed are
    8.16.2
    ,
    10.20.1
    ,
    12.18.3
    (default), and
    14.8.0
    so I have no idea where where
    12.16.1
    is coming from
    v
    • 2
    • 12
  • m

    Marc Knaup

    12/21/2020, 11:08 PM
    Is there any way (even if dirty) to call a
    suspend fun
    from a regular
    fun
    ? I only need that for unit testing a single function and can be sure that the function doesn’t actually suspend nor launch any other coroutines.
    r
    c
    • 3
    • 7
  • p

    Patrick Doering

    12/22/2020, 2:31 PM
    How can I create a npm package from a kotlin js project with all generated dependencies included?
    r
    b
    • 3
    • 3
  • t

    Tomas Kormanak

    12/23/2020, 5:31 AM
    Hi, is it possible to add custom npm repository to build.gradle.kts?
    t
    • 2
    • 1
  • a

    andylamax

    12/23/2020, 7:47 AM
    This might sound like a rookie question, but why doesn't the kotlin js compiler spit individual js files from individual kotlin files? e.g.
    src/main/kotlin
      + com.package.name
        - main.kt
        - test.kt
        - people.kt
    to be split into say
    build/intermediate/js
      + com.package.name
         - main.js
         - test.js
         - people.js
    And then let webpack pickup from there? What are the caveats?
    t
    • 2
    • 7
  • r

    Robert Jaros

    12/23/2020, 10:38 AM
    Is the fix for KT-41227 included in 1.4.30-M1? The bug is fixed, targeted for 1.4.30 but not listed in the changelog https://github.com/JetBrains/kotlin/releases/tag/v1.4.30-M1. @Dmitry Romanov [JB]
    d
    n
    • 3
    • 6
  • h

    Hamza GATTAL

    12/23/2020, 8:42 PM
    Hi the all How many times I asked how to use firebase in Kotlin/JS with react I mentioned I'm a beginner in js and KotlinJs All what i need is first step to initialise firebase then i can complete the rest alone I hope this see some answers Show me how kotliners helping others
    :kotlin: 1
    q
    • 2
    • 1
  • a

    andylamax

    12/25/2020, 4:30 AM
    What is the cause of this? and more specifically, is there a workaround? Has been happening more frequently lately and deleting the
    .gradle
    directory seemed to help but not this time
    > Task :sandbox-react:compileDevelopmentExecutableKotlinJs FAILED
    e: java.lang.IllegalStateException: org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor@25cb2023 is not bound
            at org.jetbrains.kotlin.ir.descriptors.WrappedDeclarationDescriptor.getOwner(WrappedDescriptors.kt:96)
            at org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor.getContainingDeclaration(WrappedDescriptors.kt:370)
            at org.jetbrains.kotlin.resolve.DescriptorUtils.getContainingModuleOrNull(DescriptorUtils.java:200)
            at org.jetbrains.kotlin.resolve.DescriptorUtils.getContainingModule(DescriptorUtils.java:185)
            at org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt.getModule(DescriptorUtils.kt:64)
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker.findDeserializedDeclarationForSymbol(KotlinIrLinker.kt:523)
            at org.jetbrains.kotlin.backend.common.serialization.KotlinIrLinker.getDeclaration(KotlinIrLinker.kt:566)
            at org.jetbrains.kotlin.ir.util.ExternalDependenciesGeneratorKt.getDeclaration(ExternalDependenciesGenerator.kt:60)
            at org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator.generateUnboundSymbolsAsDependencies(ExternalDependenciesGenerator.kt:50)
            at org.jetbrains.kotlin.ir.backend.js.CompilerKt.compile(compiler.kt:69)
            at org.jetbrains.kotlin.ir.backend.js.CompilerKt.compile$default(compiler.kt:51)
            at org.jetbrains.kotlin.cli.js.K2JsIrCompiler.doExecute(K2JsIrCompiler.kt:223)
            at org.jetbrains.kotlin.cli.js.K2JSCompiler.doExecute(K2JSCompiler.java:181)
            at org.jetbrains.kotlin.cli.js.K2JSCompiler.doExecute(K2JSCompiler.java:74)
            at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
            at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
            at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
            at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1560)
            at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
            at sun.rmi.transport.Transport$1.run(Transport.java:200)
            at sun.rmi.transport.Transport$1.run(Transport.java:197)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at java.lang.Thread.run(Thread.java:748)
    
    w: Detected multiple Kotlin daemon sessions at build/kotlin/sessions
    
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':sandbox-react:compileDevelopmentExecutableKotlinJs'.
    > Internal compiler error. See log for more details
    j
    v
    m
    • 4
    • 4
  • e

    Edoardo Luppi

    12/26/2020, 5:53 PM
    When using suspending functions as class functions, how do you expose them to JS as promises? Is creating wrappers the only way?
    a
    • 2
    • 6
Powered by Linen
Title
e

Edoardo Luppi

12/26/2020, 5:53 PM
When using suspending functions as class functions, how do you expose them to JS as promises? Is creating wrappers the only way?
a

andylamax

12/26/2020, 7:34 PM
yes wrapping is the only way
e

Edoardo Luppi

12/26/2020, 7:36 PM
@andylamax ouch, that's so redundant. I can't even reuse base interfaces as their methods are declared as suspendable
a

andylamax

12/26/2020, 7:42 PM
to combat that, make your base interfaces with callbacks, then add await as extension functions to your base interfaces. That way your code is easily usable all over
e

Edoardo Luppi

12/26/2020, 7:51 PM
@andylamax uh, callbacks by default seems a good idea, but I don't understand the extension functions part
a

andylamax

12/26/2020, 8:28 PM
Let me give you an exaple
interface ThingGetter {
  fun getThing(callback: (Thing)->Unit)
}

suspend fun ThingGetter.await() = suspendCancelableCoroutine {cont->
  getThing{thing->
     cont.resume(thing)
  }
}
e

Edoardo Luppi

12/26/2020, 8:30 PM
Thanks! I'll think about this!
View count: 1