我正在借助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);
}
在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