N
N
noob7772019-10-23 05:11:02
Android
noob777, 2019-10-23 05:11:02

How to build MVVM architecture logic in my application?

I have an app with one activity MainActivity.ktand activity_main.xml. Inside the activity, there is only a EditText, which I added a TextChangedListener. which makes an API request about the weather AND all the logic is in MainActivity.kt. How can I implement this with MVVM ? Do I need to somehow shove the logic TextChangedListenerinto ViewModel? Or ViewModeldoes not have access to View? Where it is necessary to implement and how it is necessary to do these requests in application?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
terminator-light, 2019-10-23
@noob777

View can call VM methods.
But there is no return.
For example, in View, i.e. in MainActivity you have code like this:

editText.addTextChangedListener(new OnTextChangedListener() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
              //вызываете метод VM
                viewModel.loadWeatherData();
            }
});
//подписываетесь на изменения данных во VM
viewModel.getWeatherData().observe(this, data -> {
          //данные изменились, можно показать тост или сделать что-то другое... Можно показать измененные данные, в конце концов
});

and in VM:
public class WeatherViewModel extends ViewModel {
      private final MutableLiveData<WeatherData> weatherData = new MutableLiveData<>();
      public LiveData<WeatherData> getWeatherData() {
        return checkout;
      }
      public void loadWeatherData(){
            //из своего API получаете данные и изменяете weatherData
            disposable.add(repository.fetchWeatherData() 
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
                .subscribe((data, throwable) -> {
                   //при вызове setValue вызывается коллбек у подписчиков на weatherData
                    this.weatherData.setValue(data);
                }
        ));
      }
}

T
tiroman, 2019-10-23
@tiroman

https://developer.android.com/jetpack/docs/guide

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question