LiveData : way to inform UI

LiveData is an observable data holder. It lets the components in your app observe LiveData objects for changes.

因为 LiveData 只在 Activity/Fragment active 时触发回调,这样就解决了2个问题:在更新UI时,不需要检查UI的状态;在配置发生变化时,会自动恢复数据。

  1. LiveData will not invoke the callback unless the fragment is in an active state. we didn't have to override the fragment's onStop() method to stop observing the data.

  2. We also didn't do anything special to handle configuration changes (for example, user rotating the screen). The ViewModel is automatically restored when the configuration changes, so as soon as the new fragment comes to life, it will receive the same instance of ViewModel and the callback will be called instantly with the current data.

@Dao
public interface WeatherDao {
    @Query("SELECT * FROM weather WHERE date = :date")
    LiveData<WeatherEntry> getWeather(Date date);

返回 LiveData<> 的原因是,当数据库发生变化时,LiveData可以触发 observers 回调。

Room has an extremely handy feature for when you want to have a LiveData object that stays in sync with whatever is in the database - Room can return LiveData wrapped objects. This LiveData will trigger its' observers any time the database data changes. It even loads this database data off of the main thread for you.