0

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

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

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

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

API接口

public interface ApiInterface {

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

}

远程数据源类

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();
        }
    });
}

带有回调的 DataSource 接口

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);
    }
4

1 回答 1

0

MoviesRepository你应该声明一个函数Callback。您Presenter 应该在调用时实现MovieDataSource.LoadMovieCallBack并传递它MoviesRepository

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

是谷歌MVP已经完成的待办事项应用示例,您可以参考。但现在它已被弃用,因为谷歌推荐MVVM

于 2020-05-25T02:06:25.727 回答