https://kotlinlang.org logo
#announcements
Title
# announcements
j

Joey

12/03/2019, 5:32 AM
how to properly call suspend functions from activities? I have this issue of wrapping each of suspend functions in
launch{}
and it looks a bit messy in my point of view. Any suggestions?
h

hellman

12/03/2019, 7:08 AM
One way is to use an extension function if you keep doing
lifecycleScope.launnch { }
in a lot of places. Something like this:
Copy code
inline fun AppCompatActivity.call(crossinline block: suspend () -> Job) {
    lifecycleScope.launch { block() }
}
But I’ve realised it is better to hide the suspending function inside a
ViewModel
and only expose non-suspend functions and
LiveData
to the
Activity
, but that is more of a personal preference.
j

Joey

12/06/2019, 7:08 AM
How to call this suspend function from kotlin library to java?
g

gildor

12/08/2019, 8:28 AM
From Kotlin to Java? What do you mean? Maybe you mean call it from Java? Short answer you cannot do this from Java, instead, expose suspend function using any asynchronous Java API: CompletableFuture, RxJava etc