gpt4 book ai didi

Android 实时数据 - 观察配置更改后始终触发

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:35 25 4
gpt4 key购买 nike

我目前正在重构我的代码以包含 ViewModel 和 android.arch 库提供的 LiveData。我有一个简单的 Activity ,它向服务器发送密码更改请求并根据 HTTP 响应代码执行操作。

为此,我创建了扩展 ViewModel 的类以获取数据,并创建了一个存储库类来调用服务器。我的 ViewModel 类有一个 MutableLiveData 字段,我正在使用 .observe(...) 方法从我的 Activity 中订阅它。问题是 .observe(...) 中的代码在配置更改(即屏幕旋转)后一直触发,我不知道为什么。

下面是相应的 ViewModel、Repository 和 Activity 类的代码:

更改密码 View 模型

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)
...
}

密码更改存储库

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);
}
}

Activity

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(...) 向服务器发送请求后观察 Activity 中的代码

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

每次旋转屏幕后都会触发。为什么会这样? MutableLiveData responseCode 的值自上次服务器调用以来尚未更新,那么如果实时数据没有更改,为什么 .observe() 会触发?

最佳答案

这是一种预期的行为,正如您在 documents 中看到的那样:

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.

如果你想观察 View 状态的变化,那么你应该创建并观察 View 状态而不是网络请求,google 已经提供了一个 example对于这样的情况。

关于Android 实时数据 - 观察配置更改后始终触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49318011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com