Answer the question
In order to leave comments, you need to log in
How to build MVVM architecture logic in my application?
I have an app with one activity MainActivity.kt
and 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 TextChangedListener
into ViewModel
? Or ViewModel
does 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
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 -> {
//данные изменились, можно показать тост или сделать что-то другое... Можно показать измененные данные, в конце концов
});
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);
}
));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question