Skip to content

Instantly share code, notes, and snippets.

@AkshayChordiya
Last active November 16, 2023 23:42
Show Gist options
  • Save AkshayChordiya/f48f42b59068bba5fa226c4535f64eef to your computer and use it in GitHub Desktop.
Save AkshayChordiya/f48f42b59068bba5fa226c4535f64eef to your computer and use it in GitHub Desktop.
FileLiveData to observe changes to file
class FileLiveData(private val context: Context) : LiveData<List<String>>() {
private val fileObserver: FileObserver
init {
val path = File(context.filesDir, "users.txt").path
fileObserver = object : FileObserver(path) {
override fun onEvent(event: Int, path: String?) {
// The file has changed, so let’s reload the data
loadData()
}
}
loadData()
}
override fun onActive() {
fileObserver.startWatching()
}
override fun onInactive() {
fileObserver.stopWatching()
}
@SuppressLint("StaticFieldLeak")
private fun loadData() {
object : AsyncTask<Void, Void, List<String>>() {
override fun doInBackground(vararg voids: Void): List<String> {
val file = File(context.filesDir, "downloaded.json")
return file.readLines()
}
override fun onPostExecute(data: List<String>) {
setValue(data)
}
}.execute()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment