Android实时数据-观察总是在配置更改后触发 [英] Android live data - observe always fires after config change

查看:218
本文介绍了Android实时数据-观察总是在配置更改后触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在重构我的代码,以将android.arch库提供的LiveData包含在ViewModel中.我有一个简单的活动,该活动将更改密码的请求发送到服务器,并根据HTTP响应代码进行操作.

I'm currently refactoring my code to include ViewModel with LiveData provided by android.arch library. I have a simple activity that sends request for a password change to server and acts according to HTTP response code.

为此,我创建了扩展用于数据的ViewModel的类和用于调用服务器的存储库类.我的ViewModel类具有一个MutableLiveData字段,我使用.observe(...)方法从我的活动中订阅该字段.问题在于.observe(...)中的代码在配置更改(即屏幕旋转)后一直触发,我不知道为什么.

For that purpose I have created class that extends ViewModel for data and a repository class to call server. My ViewModel class has one MutableLiveData field which I'm subscribing to from my activity using .observe(...) method. The issue is that code inside .observe(...) fires all the time after configuration changes (i.e. screen rotation) and I have no idea why.

以下是相应的ViewModel,Repository和Activity类的代码:

Here is the code of ViewModel, Repository and Activity classes accordingly:

ChangePasswordViewModel

ChangePasswordViewModel

public class ChangePasswordViewModel extends ViewModel{

    private MutableLiveData<Integer> responseCode;
    private PasswordChangeRepository passwordChangeRepository;

    public ChangePasswordViewModel() {
        responseCode = new MutableLiveData<>();
        passwordChangeRepository = new PasswordChangeRepositoryImpl();
    }

    public MutableLiveData<Integer> responseCodeLiveData() {
        return responseCode;
    }

    public void sendChangePasswordRequest(String newPassword){
        passwordChangeRepository.changePassword(newPassword,     passChangeCallback());
    }

    // Callback that fires after server sends a response
    private Callback passChangeCallback(){
        ...
        responseCode.postValue(serverResponse)
        ...
}

PasswordChangeRepository

PasswordChangeRepository

public class PasswordChangeRepositoryImpl {

    public void changePassword(String newPassword, Callback<Void> callback){
        //Sending new password to server and processing response in callback
        ServerCalls.changePassword(newPassword, callback);
    }
}

活动

public class ChangePasswordActivity extends AppCompatActivity{
...
    private void init(){
        //Getting appropriate view model
        passwordViewModel = ViewModelProviders.of(this).get(ChangePasswordViewModel.class);

        // Starting to observe LiveData
        passwordViewModel.getResponseCode().observe(this, responseCode -> {
           Log.info("Server response is " + responseCode);
        });

        //Sending new password to server
        buttonPassChange.setOnClickListener(view ->
            passwordViewModel.sendChangePasswordRequest("newPass")
        );
    }
...
}

问题是我第一次使用sendChangePasswordRequest(...)将请求发送到服务器后,观察活动中的代码

Problem is that after the first time I send request to server using sendChangePasswordRequest(...) observe code in activity

passwordViewModel.getResponseCode().observe(this, responseCode -> {
           Log.info("Server response is " + responseCode);
        });

每次旋转屏幕后,

都会触发.为什么会这样呢?自上次服务器调用以来,MutableLiveData responseCode的值尚未更新,那么如果实时数据没有任何更改,为什么.observe()会被触发?

fires every time after I rotate the screen. Why is that happening? Value of MutableLiveData responseCode hasn't been updated since the last server call, so why does .observe() fires if there were no changes to live data?

推荐答案

这是预期的行为,如您在

That is an intended behavior, as you can see in documents:

观察(LifecycleOwner所有者, 观察者观察者)将给定观察者添加到给定所有者的生命周期内的观察者列表中.这些事件是 在主线程上调度.如果LiveData已经设置了数据,它将 将交付给观察者.

observe (LifecycleOwner owner, Observer observer) Adds the given observer to the observers list within the lifespan of the given owner. The events are dispatched on the main thread. If LiveData already has data set, it will be delivered to the observer.

如果您想观察视图状态的变化,那么您应该创建并观察视图状态而不是网络请求,谷歌已经提供了

If you want to observe the change in view state then you should create and observe a view state instead of a network request, google already provided an example for cases like this.

这篇关于Android实时数据-观察总是在配置更改后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆