如何从MVVM体系结构中的Web服务的存储库类与活动/片段通信

时间:2018-12-18 12:09:19

标签: java android-room android-architecture-components android-livedata android-mvvm

我是MVVM architecture的新手,我只是想知道如何在repository classUI (activity/fragment) class之间进行交流。我遇到了实时数据,该数据正在完成{{ 1}}。

例如: 1)如果我有名为用户的实体。我可以使用如下实时数据保存并观察它:(来自android开发者网站)。

same entities from both (remote and room database)

2)但是如何在其他API(例如,登录)中做到这一点,这些API不需要实时数据,但我只想显示或隐藏进度对话框,这取决于网络成功或错误消息。

    public class UserRepository {
    private final Webservice webservice;
    private final UserDao userDao;
    private final Executor executor;

    @Inject
    public UserRepository(Webservice webservice, UserDao userDao, Executor executor) {
        this.webservice = webservice;
        this.userDao = userDao;
        this.executor = executor;
    }

    public LiveData<User> getUser(String userId) {
        refreshUser(userId);
        // Returns a LiveData object directly from the database.
        return userDao.load(userId);
    }

    private void refreshUser(final String userId) {
        // Runs in a background thread.
        executor.execute(() -> {
            // Check if user data was fetched recently.
            boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
            if (!userExists) {
                // Refreshes the data.
                Response<User> response = webservice.getUser(userId).execute();

                // Check for errors here.

                // Updates the database. The LiveData object automatically
                // refreshes, so we don't need to do anything else here.
                userDao.save(response.body());
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使isVerifiedUser()返回一个liveData,您可以在与该UI(活动/片段)相关的viewModel中观察该数据。

1。内部存储库:

public LiveData<State> isVerifiedUser(int userId){

    MutableLiveData<State> isVerified = new MutableLiveData();

    executor.execute(() -> {           
        Response<User> response = webservice.getVerifyUser(userId).execute();
        // Update state here.
        isVerified.postValue(valueHere)
    });

    return isVerified;
}

2。 ViewModel:

 public ViewModel(final Repository repository) {
        //observe userId and trigger isVerifiedUser when userId value is changed
        stateLiveData = Transformations.map(userId, new Function<>() {
            @Override
            public RepoMoviesResult apply(Integer userId) {
                return repository.isVerifiedUser(userId);
            }
        });
    }

3。活动:

viewModel.getStateLiveData ().observe(this, new Observer<>() {
    @Override
    public void onChanged(State state) {
         //do something here
    }
});

更多信息:

LiveData

ViewModel

Guide to app architecture MVVM