2

请看这段代码:

主要活动:

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

        MutableLiveData<User> mutableUser = new MutableLiveData<>();
        mutableUser.setValue(new User("John","Gordon","Homeless"));

        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        activityMainBinding.setHandler(new MainActivityHandler());

        activityMainBinding.setLifecycleOwner(this);
        activityMainBinding.setUser(mutableUser);

        setSupportActionBar(activityMainBinding.toolbar);
    }

MutableLiveData在xml布局中定义:

<variable name="user" type="android.arch.lifecycle.MutableLiveData&lt;test.databindingtemplate.ViewModels.User&gt;"/>

用户的每个字段都必须通过数据绑定来控制:

<EditText
                android:id="@+id/editTextName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="textPersonName"
                android:text="@={user.firstName}"
                app:layout_constraintBottom_toTopOf="@+id/textViewSecondName"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textViewSecondName"
                app:layout_constraintTop_toTopOf="parent"/>

这很好用,跟踪配置更改并将其填充到 gui(例如,当我在“名称”字段中键入内容时,屏幕旋转时值仍然存在)。

接下来,我想从 rest webservice - Retrofit/RxJava 实现刷新用户详细信息,并且我想在数据加载过程中显示繁忙指示器,例如,在onCreate方法中:

showBusyIndicator(); 
testService.getUserDetails(headers)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(user ->
                {
                  hideBusyIndicator();
                  activityMainBinding.getUser().setValue(user);
                }, throwable -> 
                {
                    Log.d(TAG, "ERROR loading user");
                    hideBusyIndicator();
                });

现在我不确定如何正确处理配置更改 - 当显示繁忙指示器时,应该在屏幕旋转更改后重新创建它。由于MutableLiveData处理配置变化很好,我无法找到任何解决方案(除了“经典”方式)来解决我在这种情况下加载指示器和处理结果的问题。

你能给我指出正确的方向吗?

[编辑] getUserDetails 声明:

@NonNull
@GET("/user")
Observable<User> getUserDetails(@HeaderMap Map<String, String> headers);

@user8035311

我修改了您的 github 示例以触发按钮单击时的模拟数据加载,这种方式(按钮已添加到布局中):

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.progressDialog = new ProgressDialog(this);
        this.progressDialog.setMessage("Loading...");

        final ActivityMainBinding mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mainBinding.setLifecycleOwner(this);

        mainBinding.button2.setOnClickListener(view ->
        {
            RxViewModel.RxViewModelFactory factory = new RxViewModel.RxViewModelFactory();
            final RxViewModel model = ViewModelProviders.of(MainActivity.this, factory).get(RxViewModel.class);
            LiveData<User> liveData = model.getLiveData();
            progressDialog.show();
            liveData.observe(MainActivity.this, s ->
            {
                progressDialog.dismiss();
                mainBinding.setUser(s);
            });

        });
    }

但这不起作用。任务在屏幕旋转时中断,但以下情况除外:

06-27 09:05:18.737 11829-11829/app.rxrotation.com.architecturecomponentsrxrotation E/WindowManager: android.view.WindowLeaked: Activity app.rxrotation.com.architecturecomponentsrxrotation.MainActivity 泄露了原本的窗口 DecorView@5b16e38[]在 android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346) 在 android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) 在 android.app 的 android.view.ViewRootImpl.(ViewRootImpl.java:485) .Dialog.show(Dialog.java:330) at app.rxrotation.com.architecturecomponentsrxrotation.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:35) at app.rxrotation.com.architecturecomponentsrxrotation.MainActivity$$Lambda$0。 onClick(Unknown Source:4) at android.view.View.performClick(View.java:6294) 在 android.os.Handler.handleCallback(Handler.java:790) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.view.View$PerformClick.run(View.java:24770) 在android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6494) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal。 os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)main(ActivityThread.java:6494) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:807)main(ActivityThread.java:6494) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:807)

在我第二次单击按钮后,数据加载甚至没有执行。

4

1 回答 1

2

您可以使用ViewModelwithLiveData在配置更改后保留您的异步任务。所以,你LiveData可能看起来像这样:

public class UserLiveData extends LiveData<User> {
    public UserLiveData() {
        setValue(new User());
    }

    public UserLiveData(Headers headers) {
        Observable<User> observable = Observable.defer(new Callable<ObservableSource<? extends User>>() {
            @Override
            public ObservableSource<? extends User> call() throws Exception {
                User user = testService.getUserDetails(headers);
                return Observable.just(user);
            }
        });

        observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DefaultObserver<String>() {
                @Override
                public void onNext(User value) {
                    setValue(value);
                }

                @Override
                public void onError(Throwable e) {
                    throw new RuntimeException(e);
                }

                @Override
                public void onComplete() {

                }
        });
    }
}

然后,您UserDetailsViewModel的情况如下:

public class UserDetailsViewModel extends ViewModel {
    private LiveData<User> userLiveData;

    public UserDetailsViewModel() {
        userLiveData = new UserLiveData();    
    }

    public void observeLiveDate(LifecycleOwner owner,
                              Observer<User> observer) {
        userLiveData.observe(owner, observer);
    }

    public void loadLiveData(Headers headers) {
        userLiveData = new UserLiveData(someArgs);
    }
}

然后你MainActivity可能如下:

public class MainActivity extends AppCompatActivity {
    private ProgressDialog progressDialog;
    private UserViewModel viewModel;
    private ActivityMainBinding mainBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.progressDialog = new ProgressDialog(this);
        this.progressDialog.setMessage("Loading...");

        mainBinding = DataBindingUtil.setContentView(this,
            R.layout.activity_main);
        mainBinding.setLifecycleOwner(this);

        viewModel = ViewModelProviders.of(this).get(UserViewModel.class);

        observeLiveData();
        mainBinding.button2.setOnClickListener(v -> {
            viewModel.initLiveData(<your headers>);
            observeLiveData();
        });
    }

    private void observeLiveData() {
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);
        viewModel.observeRxLiveDate(this, user -> {
            progressDialog.dismiss();
            mainBinding.setUser(user);
        });
    }
}

我在这里创建了一个非常简单的示例

于 2018-06-14T16:49:23.577 回答