我有一个简单的应用程序,其中显示了电影列表。当用户单击一个按钮时,它应该刷新列表,这意味着再次转到翻新并获取新列表。 问题是,此刷新无效。当我打开应用程序时,它只会获取一次列表。
public class MoviesViewModel extends AndroidViewModel {
private MutableLiveData<Resource<List<Movie>>> mLastdMovieListObservable;
private Repository mRepository;
public MoviesViewModel(Application application) {
super(application);
mRepository = new Repository();
}
public LiveData<Resource<List<Movie>>> getMovieListLiveData() {
if (mLastdMovieListObservable == null) {
mLastdMovieListObservable = mRepository.getMovieList();
}
return mLastdMovieListObservable;
}
}
和存储库:
public MutableLiveData<Resource<List<Movie>>> getMovieList() {
final MutableLiveData<Resource<List<Movie>>> data = new MutableLiveData<>();
data.setValue(Resource.loading(null));
mInterface.getMovies(.....).enqueue(new Callback<MovieListResponse>() {
@Override
public void onResponse(Call<MovieListResponse> call, Response<MovieListResponse> response) {
if (response.isSuccessful()) {
data.postValue(Resource.success(response.body().getResult()));
} else {
data.postValue(Resource.error(response.message(), null));
}
}
@Override
public void onFailure(Call<MovieListResponse> call, Throwable t) {
data.postValue(Resource.error(t.getMessage(), null));
}
});
return data;
}
然后在片段中只是:
mMoviesViewModel.getMovieListLiveData().observe(this, moviesResource -> {
if (moviesResource.status == Status.SUCCESS) {
.....
.....
然后单击按钮部分,当我需要再次获取列表时,我不确定如何实现它。 我尝试的任何方法均无效。存储库立即将数据返回为null。
答案 0 :(得分:0)
您可以使用重试方法,并且我快速更改了代码以获取重试示例,并检查此源以获取更好的代码。LINK
Transformations.switchMap侦听重试,当它更改时,将再次调用swithMap。并且在UI ViewModel中应按如下所示进行配置,但在按钮中您只需调用重试即可。
mMoviesViewModel.getMovieListLiveData().observe(this, moviesResource -> {
if (moviesResource.status == Status.SUCCESS) {
.....
.....
在按钮上:
mMoviesViewModel.retry()
还有ViewModel:
public class MoviesViewModel extends AndroidViewModel {
private MutableLiveData<Resource<List<Movie>>> mLastdMovieListObservable;
private Repository mRepository;
private Boolean mRetry = false;
public MoviesViewModel(Application application) {
super(application);
mRepository = new Repository();
mLastdMovieListObservable = Transformations.switchMap(mRetry){
mLastdMovieListObservable = mRepository.getMovieList()
}
}
public LiveData<Resource<List<Movie>>> getMovieListLiveData() {
return mLastdMovieListObservable;
}
public void retry(){
mRetry.setValue(true)
}}
答案 1 :(得分:0)
电影类型的更改如下:
public class MoviesViewModel extends AndroidViewModel {
private MutableLiveData<Resource<List<Movie>>> mLastdMovieListObservable;
private Repository mRepository;
private Int mMovieType = 0;
public MoviesViewModel(Application application) {
super(application);
mRepository = new Repository();
mLastdMovieListObservable = Transformations.switchMap(mMovieType, type->
mLastdMovieListObservable = mRepository.getMovieList(type)
);
}
public LiveData<Resource<List<Movie>>> getMovieListLiveData() {
return mLastdMovieListObservable;
}
public void setMovieType(Int movieType){
mMovieType.setValue(movieType)
}
}