AAC:如何从ViewModel返回结果(处理点击)到活动?

问题描述 投票:0回答:1

我想在我的项目Android Architecture Components(AAC)中使用。尼斯。

我的活动在这里:

    import androidx.appcompat.app.AppCompatActivity;
    public class TradersActivity extends AppCompatActivity  {
        private TradersViewModel tradersViewModel;

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


              tradersViewModel = ViewModelProviders.of(this).get(TradersViewModel.class);

              tradersViewModel.getIsEnableSwipeProgress().observe(this, new Observer<Boolean>() {

                    @Override
                    public void onChanged(Boolean isEnable) {
                        // do some work with UI
                    }
                });

        }

        // button click        
        public void onClickViewJson(Trader trader) {
             tradersViewModel.doClickJsonView(trader);
        }

    }

这是我的ViewModel

public class TradersViewModel extends ViewModel {
private MutableLiveData<Boolean> isEnableSwipeProgress = new MutableLiveData<>();

 public void doClickJsonView(Trader trader) {
      // DO_SOME_COMPLEX_BUSINESS_LOGIC
 }

 public MutableLiveData<Boolean> getIsEnableSwipeProgress() {
      return isEnableSwipeProgress;
 }

}

在屏幕上我有按钮。当点击这个按钮时,我会调用activity的方法 - onClickViewJson(Trader trader)

这个方法叫tradersViewModel.doClickJsonView(trader);

viewModel中,这种方法做了一些复杂的业务逻辑。方法完成后,我需要将结果(json)返回到我的活动。

我怎么能这样做?

mvvm android-architecture-components
1个回答
1
投票

请记住,在MVVM中,ViewModels并不了解您的视图。您的ViewModel应该公开变量,以便您的视图可以观察并对它们做出反应。

 private MutableLiveData<Boolean> isEnableSwipeProgress = new MutableLiveData<>();

 private MutableLiveData<JSONDto> jsonLiveData = new MutableLiveData<>();

 public void doClickJsonView(Trader trader) {
      // DO_SOME_COMPLEX_BUSINESS_LOGIC
      jsonLiveData.postValue(/* the json you obtain after your logic finish */ )
 }

 public MutableLiveData<Boolean> getIsEnableSwipeProgress() {
      return isEnableSwipeProgress;
 }

 public LiveData<JSONDto> getJsonDto() {
      return this.jsonLiveData;
 }


在您看来,您对jsonDto的变化作出反应:

tradersViewModel.getJsonDto().observe(this, new Observer<JSONDto>() {

                    @Override
                    public void onChanged(JSONDto json) {
                         if (json != null) {
                           // Do what you need here.
                         }
                    }
                });
© www.soinside.com 2019 - 2024. All rights reserved.