I am trying to load image from server to ImageView
button.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
val url = mainApi.loadMyImage()
Picasso.with(requireContext()).load(url)
.into(imgView)
}
}
And getting error for Picasso:
java.lang.IllegalStateException: Method call should happen from the main thread.
Could you explain me the correct way to communicate between main thread and CoroutineScope
in my code?
When you want to change the UI, you have to do it on the main thread. So, you get data in the IO thread and then update the UI on the main thread
Here is the code:
button.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
val url = mainApi.loadMyImage()
withContext(Dispatchers.Main){
Picasso.with(requireContext()).load(url)
.into(imgView)
}
}
}