How to call suspend function from Fragment or Activity?
You can either use
GlobalScope.launch {
}
or
Make your fragment/activity implement CoroutineScope
and set default Dispatcher like this.
class Fragment : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
. . .
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
Then you can call suspend function like the code you attached in the question.
Update
The coroutine scope for activity/fragment can be defined like this.
class Fragment : CoroutineScope by MainScope() {
...
override fun onDestroy() {
super.onDestroy()
cancel()
}
}
In documentation https://developer.android.com/topic/libraries/architecture/coroutines said that I can use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
ktx.
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}