我如何在Model View Presenter模式中使用存储库模式和Interactor模式?

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

我正在借助Model View Presenter模式开发应用程序。

我利用了Retrofit,所以我有一个带有端点的ApiClient和ApiInterface。我在Repository类中调用的RemoteDataSource类中实现了接口。

我的问题是-我如何利用Interactor类使存储库与Presenter通信?

到目前为止,这是我的代码:

ApiInterface

public interface ApiInterface {

@GET("?")
Call<ArrayList<Movie>> getMoviesByTitle(@Query("t") String title,@Query("apiKey") String apiKey);

}

RemoteDataSource类

private static MovieRemoteDataSource instance;
private final ApiInterface service;

public MovieRemoteDataSource(ApiInterface movieApi) {
    service = ApiClient.createService(ApiInterface.class);
}

public static MovieRemoteDataSource getInstance(ApiInterface movieApi) {
    if (instance == null) {
        instance = new MovieRemoteDataSource(movieApi);
    }
    return instance;
}

@Override
public void getMovies(String title, String apiKey, final LoadMovieCallBack callback) {
    service.getMoviesByTitle(title,apiKey).enqueue(new Callback<ArrayList<Movie>>() {
        @Override
        public void onResponse(Call<ArrayList<Movie>> call, Response<ArrayList<Movie>> response) {
            ArrayList<Movie> movies = response.body();// != null ? //response.body().getTitle() : null;
            if (movies != null && !movies.isEmpty()) {
                callback.onMoviesLoaded(movies);
            } else {
                callback.onDataNotAvailable();
            }
        }

        @Override
        public void onFailure(Call<ArrayList<Movie>> call, Throwable t) {
            callback.onError();
        }
    });
}

带有回调的数据源接口

public interface MovieDataSource {
    interface LoadMovieCallBack{
        void onMoviesLoaded(ArrayList<Movie> movies);
        void onDataNotAvailable();
        void onError();

    }

    void getMovies(String title, String apiKey,LoadMovieCallBack callback);

}

存储库

 private MovieRemoteDataSource movieRemoteDataSource;


public MoviesRepository() {//ApiInterface movieApi) {
    //this.service = ApiClient.createService(ApiInterface.class);
}

public static MoviesRepository getInstance(ApiInterface service) {
    if (instance == null) {
        instance = new MoviesRepository();
    }
    return instance;
}





  public void getMovies(String title, String apiKey ) {
        movieRemoteDataSource.getMovies(title,apiKey,this);
    }
java android repository-pattern mvp interactors
1个回答
0
投票

MoviesRepository中,您应使用Callback声明一个函数。您的Presenter 应该实现MovieDataSource.LoadMovieCallBack并在调用MoviesRepository时将其传递

  public void getMovies(String title, String apiKey,MovieDataSource.LoadMovieCallBack callback) {
        movieRemoteDataSource.getMovies(title,apiKey,callback);
  }

[Here是Google MVP已经完成了待办事项应用程序示例,您可以参考它。但是现在不推荐使用,因为Google建议MVVM

© www.soinside.com 2019 - 2024. All rights reserved.