在存储库之间进行通信->查看模型->活动

时间:2019-07-14 05:35:26

标签: android mvvm android-livedata

  • 我有一个活动附加到具有存储库的视图模型上
  • 目前,我正在使用一个界面来处理来自 存储库以查看模型,然后使用实时数据处理 活动

问题:如何删除界面并实现相同的功能,我遇到了需要使用转换的问题。怎么做

MainActivityViewModel.java

public class MainActivityViewModel extends AndroidViewModel implements IntProgressCallback, IntErrorMessageCallback {

    private MovieServerRepository movieServerRepository;
    private MovieLocalRepository localRepository;

    private MutableLiveData<Boolean> liveProgress = new MutableLiveData<>();
    private MutableLiveData<String> liveErrorMessage = new MutableLiveData<>();

    public MainActivityViewModel(@NonNull Application application) {
        super(application);
        //Instantiate the repository
        movieServerRepository = new MovieServerRepository(application,this,this);
        localRepository = new MovieLocalRepository(application,this);
    }

    @Override
    public void progressStart() {
        liveProgress.postValue(true);
    }

    @Override
    public void progressStop() {
        liveProgress.postValue(false);
    }

    @Override
    public void displayErrorMessage(String message) {
        liveErrorMessage.postValue(message);
    }

    /** ********************************* LIVE DATA ********************************************* **/
    /** LIVE-DATA, For data received from server **/
    public LiveData<List<Movie>> getAllMovies() {
        return movieServerRepository.getPopularMovies();
    }

    /** LIVE-DATA, inserted into local database **/
    public LiveData<List<Movie>> insertMoviesIntoLocalDatabase(List<Movie> movies) {
        return localRepository.createMovie(movies);
    }

    /** LIVE-DATA, for progress states **/
    public MutableLiveData<Boolean> getLiveProgress() {
        return liveProgress;
    }

    /** LIVE-DATA, for Error message states **/
    public MutableLiveData<String> getLiveErrorMessage() {
        return liveErrorMessage;
    }
    /** ********************************* LIVE DATA ********************************************* **/


    /** Clear disposables **/
    public void clearDisposables() {
        movieServerRepository.clearDisposables();
        localRepository.clearDisposables();
    }



}

MovieServerRepository.java

    public class MovieServerRepository {

        private Application application;
        private List<Movie> movies = new ArrayList<>();
        private Observable<PopularMovies> movieDBResponseObservable;
        private MovieDataService movieDataService;

        private CompositeDisposable compositeDisposable = new CompositeDisposable();
        private MutableLiveData<List<Movie>> liveData = new MutableLiveData<>();

        private IntProgressCallback progressCallback;
        private IntErrorMessageCallback errorMessageCallback;

        public MovieServerRepository(Application application,
                                     MainActivityViewModel progressCallback,
                                     MainActivityViewModel errorMessageCallback) {
            this.application = application;
            this.progressCallback = progressCallback;
            this.errorMessageCallback = errorMessageCallback;
            setRetrofitClient();
            initObservable();
        }

        /************************************* INIT FUNCTIONS ******************************************/
        private void initObservable() {
            movieDBResponseObservable = movieDataService.getPopularMovies(Keys.API_KEY);
        }

        /** Retrofit client **/
        private void setRetrofitClient() {
            movieDataService = RetrofitInstance.getService();
        }
        /************************************* INIT FUNCTIONS ******************************************/

        /** Clear disposables **/
        public void clearDisposables() {
            if(compositeDisposable !=null && !compositeDisposable.isDisposed()){
                compositeDisposable.dispose();
            }
        }

        /************************************* MUTABLE DATA ********************************************/
        /** Live data **/
        public MutableLiveData<List<Movie>> getPopularMovies() {
            compositeDisposable.add(getServerDataDisposable());
            return liveData;
        }
        /************************************* MUTABLE DATA ********************************************/

        /************************************* DISPOSABLES *********************************************/
        /** Disposable for server data **/
        private Disposable getServerDataDisposable() {
            return movieDBResponseObservable
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .flatMap((Function<PopularMovies, Observable<Movie>>) movieDBResponse -> Observable.fromArray(movieDBResponse.getResults().toArray(new Movie[0])))
                    .filter(movie -> true)
                    .subscribeWith(getObserver());
        }

        /** DisposableObserver for movies list from server data **/
        private DisposableObserver getObserver() {
            progressCallback.progressStart();
            return new DisposableObserver<Movie>() {
                @Override
                public void onNext(Movie movie) {
                    movies.add(movie);
                }

                @Override
                public void onError(Throwable e) {
                    progressCallback.progressStop();
                    errorMessageCallback.displayErrorMessage(e.getMessage());
                }

                @Override
                public void onComplete() {
                    liveData.postValue(movies);
                    progressCallback.progressStop();
                }
            };
        }
        /************************************* DISPOSABLES *********************************************/

    }

MainActivity.java

public class MainActivity extends AppCompatActivity implements IntProgressCallback {

    private RecyclerView recyclerView;
    private MovieAdapter movieAdapter;

    private Loading loading;
    private Call<PopularMovies> call;

    private Observable<PopularMovies> movieDBResponseObservable;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    //private MoviesAppDatabase moviesAppDatabase;

    private MainActivityViewModel activityViewModel;

    @Inject
    public MoviesAppDatabase moviesAppDatabase;

    /************************************ Life Cycle Methods ***************************************/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initOnCreate();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        initOnDestroy();
    }
    /************************************ Life Cycle Methods ***************************************/

    @Override
    public void progressStart() {
        startLoading();
    }

    @Override
    public void progressStop() {
        stopLoading();
    }


    /************************************ Init Methods *********************************************/
    /** INIT onCreate **/
    private void initOnCreate() {
        setContentView(R.layout.activity_main);
        App.getApp().getMovieAppComponent().inject(this);
        findViews();
        initViewModel();
        showOnRecyclerView();
        getPopularMovies();
        progressStates();
        errorMessages();
    }

    /** INIT onDestroy **/
    private void initOnDestroy() {
        if(compositeDisposable !=null && !compositeDisposable.isDisposed()){
            compositeDisposable.dispose();
        }
        activityViewModel.clearDisposables();
    }
    /************************************ Init Methods *********************************************/

    /************************************ Custom Methods *******************************************/

    /** Find views for the screen **/
    private void findViews() {
        recyclerView = findViewById(R.id.rvMovies);
        loading = findViewById(R.id.loading);
    }


    /** Init view model **/
    private void initViewModel() {
        activityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
    }

    /** Set up RecyclerView **/
    private void showOnRecyclerView() {
        movieAdapter = new MovieAdapter(this);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        }

        recyclerView.setLayoutAnimation(AnimationUtils.loadLayoutAnimation(this, R.anim.grid_layout_animation_from_bottom));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(movieAdapter);
    }

    /** Stop loading **/
    private void stopLoading() {
        loading.Cancel();
    }

    /** Start Loading **/
    private void startLoading() {
        loading.Start();
    }
    /************************************ Custom Methods *******************************************/

    /************************************ LIFE CYCLE CALLBACKS *************************************/
    public void getPopularMovies() {

        /** Single call from server **/
        /*activityViewModel.getAllMovies().observe(this, new Observer<List<Movie>>() {
            @Override
            public void onChanged(List<Movie> movies) {
                Log.d("",movies+"");
                mMovies = movies;
            }
        });*/

        /** Combining two live data  **/
        Transformations.switchMap(
                                    activityViewModel.getAllMovies(), (x) ->
                                            activityViewModel.insertMoviesIntoLocalDatabase(x))
                                    .observe(this, movies ->
                                            movieAdapter.setData(new ArrayList<>(movies))
                                );



    }

    /** Progress States **/
    private void progressStates() {
        activityViewModel.getLiveProgress().observe(this, newValue -> {
            if(newValue){
                startLoading();
            }else{
                stopLoading();
            }
        });
    }

    /** Error Messages **/
    private void errorMessages() {
        activityViewModel.getLiveErrorMessage().observe(this, newValue -> Toast.makeText(this,newValue,Toast.LENGTH_LONG).show());
    }
    /************************************ LIFE CYCLE CALLBACKS *************************************/


}

1 个答案:

答案 0 :(得分:0)

由于存储库中只有progressStartprogressStop回调,为什么在存储库本身中没有MutableLiveData<Boolean>并将其作为LiveData<Boolean>公开给ViewModel?然后,视图模型可以将其直接暴露给活动。