ViewModel LiveData setValue()

ViewModel 官网
1、
        private MutableLiveData> users;
        public LiveData> getUsers() {
            if (users == null) {
                users = new MutableLiveData>();
                loadUsers();
            }
            return users;
        }

       
/**
 * 1、
 * 关于setValue 。需要在主线程设置值,否则报错,
 * 异步任务完成后切换线程,使用Handler,rx。
 */
private void loadUsers() {
    // Do an asynchronous operation to fetch users.
    Observable.create((ObservableOnSubscribe>) emitter -> {
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
                Log.e(TAG, "loadUsers: ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            User user = new User();
            user.name = "name==" + i;
            list.add(user);
            emitter.onNext(list);
        }
        emitter.onComplete();

    }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Observer>() {
        @Override
        public void onSubscribe(Disposable d) {
            disposable = d;
        }

        @Override
        public void onNext(List list) {
            users.setValue(list);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    });


}
  2、viewModel.getUsers().observe(this, users -> Log.e(TAG, "onChanged: " + users.size()));

3、源码
private static void assertMainThread(String methodName) {
if (!ArchTaskExecutor.getInstance().isMainThread()) {
throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
+ " thread");
}
}

 

你可能感兴趣的:(ViewModel LiveData setValue())