Last active
November 16, 2023 23:42
-
-
Save AkshayChordiya/f48f42b59068bba5fa226c4535f64eef to your computer and use it in GitHub Desktop.
FileLiveData to observe changes to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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