更新 MutableLiveData 时可观察到抛出异常

Observable throwing Exception When Updating MutableLiveData

我在尝试更新我的 MutableLiveData 时遇到问题。我正在从我的 ViewModel 调用登录函数来更新我的 UI。在我的 ViewModel 中,我调用了我的 API 服务器,但是当我调用 .notify() 时,我遇到了崩溃:

java.lang.IllegalMonitorStateException: object not locked by thread before notify()

我应该把它放在哪里才能正常工作

这是我的 XML 文件

    <data>
        <variable
            name="viewModel"
            type="com.kidzmedia.radio.activities.login.LoginViewModel" />
    </data>

....

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="96dp"
        android:onClick="@{() -> viewModel.doLogin()}"
        android:text="Login" />

我的视图模型

public class LoginViewModel extends ViewModel {
    private MutableLiveData<User> userMutableLiveData;

....

    public void doLogin() {
        userMutableLiveData = userApi.loginUser(email, password);
        Log.i("LOGIN", "do Login");

        //userMutableLiveData.setValue(tmpUser.getValue());
    }

    LiveData<User> getUser() {
        if (userMutableLiveData == null) {
            userMutableLiveData = new MutableLiveData<>();
        }

        return userMutableLiveData;
    }

我的UI

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityLoginBinding activityLoginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        //activityLoginBinding.setViewModel(ViewModelProviders.of(this).get(LoginViewModel.class);

        LoginViewModel loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        activityLoginBinding.setViewModel(loginViewModel);

        loginViewModel.getUser().observe(this, new Observer<User>() {

            @Override
            public void onChanged(User user) {
                if (user != null)
                    // DO STUFF
            }
        });
    }
}

我的Api服务器:

public class UserApi {

    private final String TAG = getClass().getSimpleName();

    public MutableLiveData<User> loginUser(String email, String password) {


        User loginUser = new User(email, password);

        final MutableLiveData<User> mutableLiveData = new MutableLiveData<>();

        UserService userApi = APIUtils.getUserService();
        userApi.doLoginUser(loginUser).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                mutableLiveData.setValue(response.body());

                // THIS IS WHERE IT CRASHES
                mutableLiveData.notify();
            }
        });

        return mutableLiveData;
    }

回答您的评论

if I remove the ".notify()", then how can I get the MutableLiveData to update?

我只知道两种方法。可能对你有帮助。

  1. 您可以在参数中向 loginUser() 发送回调函数。

  2. 您可以使用 execute 而不是 enqueue 并同步处理请求。但是您需要在另一个线程中执行此操作。