https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Marc Knaup

10/15/2020, 12:47 AM
Is there a way to check if coroutines are available?
if (coroutinesAvailable) GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { … } else …
s

streetsofboston

10/15/2020, 12:57 AM
Not sure what you mean. When would they be unavailable while your code still compiles..?
z

Zach Klippenstein (he/him) [MOD]

10/15/2020, 12:58 AM
You can add coroutines as a compile-only dependency, then at runtime use reflection to try to load the
GlobalScope
class, and if it loads successfully, then make assume coroutines are available and actually make the calls. But watch out for version mismatches, you could get LinkageErrors if the runtime version of coroutines is different than what you compiled with. It’s pretty hacky, so i wouldn’t do that unless you have a really good reason.
m

Marc Knaup

10/15/2020, 1:06 AM
@Zach Klippenstein (he/him) [MOD] yup, but that doesn’t work on native though. I wonder if there can be platforms or scenarios where the coroutines library is there but you cannot start any coroutine because there is no dispatcher available.
I really miss a dynamic detection of dependencies.
if (library x is installed) …
g

gildor

10/15/2020, 3:33 AM
looks as not a good solution imo, if you want provide 2 behaviours depending on dependency. abstract it and provide outside, and put each implementation to own library
m

Marc Knaup

10/15/2020, 3:45 AM
That’s what I’d like to avoid (not in this case but in general). I’d create multi-dimensional feature libraries 😅
my-lib-with-di-with-bson-with-graphql
my-lib-with-di-without-bson-with-graphql
my-lib-with-di-without-bson-without-graphql
g

gildor

10/15/2020, 3:49 AM
why do you want to avoid it? I don’t know your use case of course, but I would prefer library which allows me provide some abstraction and or provide a few ready to use abstraction which depend on particular libraries, rather than try to be smart
anyway dynamic resolution like this may probably work with compileOnly dependencies, it definitely possible to achieve on JVM and JS, but not sure how it will work with native
m

Marc Knaup

10/15/2020, 1:09 PM
I assume you’re thinking about a typical simple scenarios:
log-library
->
log-library-slf4j
+
log-library-jul
etc. I’m talking about breaking large libraries or frameworks into composable smaller libraries. My framework has many components that you can mix as you need like MongoDB, GraphQL, Dependency Injection etc. Now if you add “MongoDB” for example the component would dynamically check if you also use “Dependency Injection” and if so would provide “MongoDB”-specific dependencies through that DI component. That only works if I can do that dynamically, otherwise I’d add a lot of dependencies although the user doesn’t use them. Unfortunately
compileOnly
is absolutely not usable on native 😕
3 Views