Launch a coroutine from a click event in a fragment
You need a job
to handle the coroutine cancelation to prevent leaks:
//inside Fragment
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
//late in the button click
button.setOnClickListener{
uiScope.launch(Dispatchers.IO){
//asyncOperation
withContext(Dispatchers.Main){
//ui operation
}
}
}
//later in on destroy:
override fun onDestroy(){
job.cancel()
super.onDestroy()
}
You can also use LifecycleScope extension from Google:
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}
Edit, in case you would re-fire another operation. Just use the same scope:
//let's assume you have a second button
button2.setOnClickListener{
uiScope.launch(Dispatchers.IO){
//perform second operation
}
}