I have several repository classes in my code.
For example, this is UserRepository:
public class UserRepository {
public static String TAG = "UserRepository";
ApiService mApiService;
SharedPreferences mPrefs;
Context mContext;
RemoteDataSource<User> mRemoteDataSource;
public UserRepository() {
mApiService = new RetrofitClient().getApiService();
mContext = App.getAppContext();
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mRemoteDataSource = new RemoteDataSource<>();
}
public RemoteDataSource getRemoteDataSource() {
mRemoteDataSource.setIsLoading();
Call<ApiResponse> userCall = mApiService.getUserInfo(mPrefs.getString(User.TOKEN_NAME, null));
userCall.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
mRemoteDataSource.setIsLoaded();
mRemoteDataSource.setData(response.body().getUser());
mRemoteDataSource.setStatus(response.body().getStatus());
mRemoteDataSource.setMessage(response.body().getMessage());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.e(TAG, t.getMessage());
mRemoteDataSource.setFailed(t.getMessage());
}
});
return mRemoteDataSource;
}
}
And this is BonusRepository:
public class BonusRepository {
public static String TAG = "BonusRepository";
ApiService mApiService;
SharedPreferences mPrefs;
Context mContext;
LiveData<Bonus> mBonus;
String mId;
RemoteDataSource<Bonus> mRemoteDataSource;
public BonusRepository(String id) {
mId = id;
mApiService = new RetrofitClient().getApiService();
mContext = App.getAppContext();
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mRemoteDataSource = new RemoteDataSource<>();
}
public RemoteDataSource getRemoteDataSource() {
mRemoteDataSource.setIsLoading();
Call<ApiResponse> bonusCall = mApiService.getBonus(mPrefs.getString(User.TOKEN_NAME, null), mId);
bonusCall.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
mRemoteDataSource.setIsLoaded();
mRemoteDataSource.setData(response.body().getBonus());
mRemoteDataSource.setStatus(response.body().getStatus());
mRemoteDataSource.setMessage(response.body().getMessage());
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.e(TAG, t.getMessage());
mRemoteDataSource.setFailed(t.getMessage());
}
});
return mRemoteDataSource;
}
}
getRemoteDataSource methods in both classes are equal, except
Call<ApiResponse> userCall = mApiService.getUserInfo(mPrefs.getString(User.TOKEN_NAME, null));
and mRemoteDataSource.setData(response.body().getUser()); in UserRepository
differs with:
Call<ApiResponse> bonusCall = ApiService.getBonus(mPrefs.getString(User.TOKEN_NAME, null), mId);
and mRemoteDataSource.setData(response.body().getBonus()); in BonusRepository.
In other repositories I have similar duplicate code.
I want to remove this duplications, but doesn't find any good solution.
What is the best way to DRY my code?