Android MVVM - 在数据更改时更新 ViewModel

Android MVVM - Update ViewModel when data changes

我正在开发一个使用 MVVM 模式和 RxJava 的应用程序。架构如下:

这是我第一次使用这种模式,我不确定在数据发生变化时更新 ViewModel(以及相应的 View)的最佳方式,由应用程序的另一个组件制作。

例如:假设我们有一个 Activity 显示我关注的用户列表(如社交应用程序),从这个列表中我 select 一个用户并在另一个 Activity。现在,从这第二个 Activity 我决定取消关注用户,当我按后退按钮到 return 到第一个 Activity 我希望列表自动更新(删除相应的用户,显然无需重新下载所有数据)。

问题是两个Activity有两个不同的ViewModel。我怎样才能使第二个 Activity 所做的更改影响第一个 ViewModel 的更改? Repository 是否有责任将更改通知第一个 Activity

非常感谢!

i decide to unfollow the user and when i press the back button to return to the first Activity i would like the list to be updated automatically (deleting the corresponding user, obviously without having to re-download all the data).

The problem is that the two Activity have two different ViewModel.

我以为你有一个存储库,它包装了一个能够公开 LiveData<*> 的“模型”(本地数据源),不是吗?

在这种情况下,您需要做的就是:

@Dao
public interface ItemDao {
    @Query("SELECT * FROM ITEMS")
    LiveData<List<Item>> getItemsWithChanges();

    @Query("SELECT * FROM ITEMS WHERE ID = :id")
    LiveData<List<Item>> getItemWithChanges(String id);
}

现在您的存储库可以return 来自 DAO 的 LiveData:

public class MyRepository {
    public LiveData<List<Item>> getItems() {
        // either handle "fetch if needed" here, or with NetworkBoundResource
        return itemDao.getItemsWithChanges();
    }
}

您在 ViewModel 中得到的:

public class MyViewModel extends ViewModel {
    private final LiveData<List<Item>> items;

    public MyViewModel(MyRepository repository) {
        this.items = repository.getItems();
    }

    public LiveData<List<Item>> getItems() {
        return items;
    }
}

如果您观察到这一点,那么当您修改 Room 中的项目时,它会自动更新 onStart 中的 LiveData(当您再次开始观察时)。