how to properly call suspend functions from activi...
# announcements
j
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
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
How to call this suspend function from kotlin library to java?
g
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