Using an excecutor for threading in LiveData
from the CommonsWare Community archivesAt April 10, 2019, 8:14pm, jQrgen asked:
In the Android JetPack book why is an excecutor used ColorLiveData? (pasted Belov):
package com.commonsware.jetpack.sampler.livedata
import android.os.SystemClock
import androidx.lifecycle.LiveData import java.util.*
import java.util.concurrent.Executors
class ColorLiveData : LiveData<List<Int>>() {
private val random = Random()
private val executor = Executors.newSingleThreadExecutor()
override fun onActive() { super.onActive()
if (value == null) { executor.execute {
SystemClock.sleep(2000) // use only for book samples!
postValue(generateSequence { random.nextInt() }.take(25).toList()) }
}}
}
According to the LiveData documentation LiveData already runs on a worker thread.
Thanks
Jørgen
At April 10, 2019, 10:06pm, mmurphy replied:
Objects do not run on threads. Functions do.
I do not see anywhere in the documentation that you linked to that implies that onActive()
is called on a background thread. And the source code of LiveData
does not show any signs of starting any threads.
So, AFAIK, what I have here is correct.
At April 11, 2019, 10:37am, jQrgen replied:
Ok thanks!
Any pointers on how i should approach learning about threads now that i have to choose inbetween androidx and old frameworks for threads?
My first goal is to fix JANK in an app i have released to google play.
jQrgen
At April 11, 2019, 10:57am, mmurphy replied:
Right now, that’s a subject that I cover more in The Busy Coder’s Guide to Android Development, albeit using first-generation Android app development techniques.
I will be covering Kotlin coroutines and other threading options in Elements of Android Jetpack and Exploring Android in the coming months.
I don’t completely follow that. Other than AsyncTask
being commonly frowned upon, and WorkManager
being added as an option for non-UI work, there has not been a lot of change related to threading itself.
For example, this topic started off with LiveData
. LiveData
is not related to threads, strictly speaking. It is purely a lifecycle-aware value holder with an observer mechanism. We tend to use it as a way of forwarding asynchronous results to activities and fragments, but LiveData
on its own has no threads.
Positively identify where the jank is coming from. From there, we can discuss specific ways to fix it. For example, if the jank is coming from loading images on the main application thread, the typical solution is to use Glide, Picasso, or another image-loading library that handles the bulk of the work on a background thread.