I have a sharedViewModel with LiveData properties.
MainActivity:
private val logViewModel by viewModels<LogViewModel>()
fun startLocationUpdates() {
val locationItem = LocationItem(...)
logViewModel.addLogEntry(locationItem)
}
override fun onCreate(savedInstanceState: Bundle?) {
val observer = object : FileObserver(applicationContext.filesDir.path + "/" + jsonFileName) {
override fun onEvent(event: Int, file: String?) {
if (event == FileObserver.MODIFY) {
loadLogViewModel()
}
}
}
observer.startWatching()
}
fun loadLogViewModel() {
val json = getData(this)
val myType = object : TypeToken<ArrayList<LocationItem>>() {}.type
if (json != null) {
val listItems: ArrayList<LocationItem> = gson.fromJson(json, myType)
for (item in listItems) {
logViewModel.addLogEntry(item)
}
}
}
LogFragment:
private val logViewModel: LogViewModel by activityViewModels()
logViewModel.locationListItems.observe(requireActivity()) {
locationItemAdapter.updateLocations()
}
LogViewModel:
class LogViewModel : ViewModel() {
var locationListItems: MutableLiveData<LocationItem> = MutableLiveData<LocationItem>()
fun addLogEntry(locationItem: LocationItem) {
locationListItems.postValue(locationItem)
}
}
When I execute startLocationUpdates()
it all works as expected. The observer gets notifications.
But when the logfile (json) is changed through the WorkManager (potentially within a different process/thread) and the FileObserver kicks in to load the JSON file and adds them to the LogViewModel, the Live data is not firing anything.
Why does it make a difference if the fileObserver
is doing it, or if startLocationUpdates()
would be doing it? I can only assume this is a threading issue. But I thought LivaData deals with that?