Dagger + Otto architecture guidance - android

I am trying to develop an app with a somewhat modular architecture (nobody knows about no one, but everybody still can communicate). I will begin with an example:
Inside the LoginFragment:
#OnClick
void login() {
bus.post(new AuthorizeEvent(email, password)); // bus is a Bus from Otto
}
#Subscribe
public void onAuthorizedEvent(AuthEvent event) {
// ... user was authorized
}
The Authenticator catches this event and then posts back:
#Subscribe
public void onAuthorizeEvent(AuthorizeEvent event) {
// ... login
bus.post(new AuthEvent(user));
}
Authenticator depends on a lot of stuff through Dagger:
#Inject
public Authenticator(ApiService apiService, Context context, Bus uiBus, Scheduler ioScheduler,
Scheduler uiScheduler) {
this.apiService = apiService;
this.context = context;
this.uiBus = uiBus;
this.ioScheduler = ioScheduler;
this.uiScheduler = uiScheduler;
uiBus.register(this);
}
which is provided by the AuthModule:
#Module(
complete = false,
library = true,
includes = {
ApiModule.class,
ApplicationModule.class
}
)
public class AuthModule {
#Provides
#Singleton
Authenticator provideAuthenticator(ApiService apiService, #ForApplication Context context,
#UIBus Bus uiBus, #IOScheduler Scheduler ioScheduler,
#UIScheduler Scheduler uiScheduler) {
return new Authenticator(apiService, context, uiBus, ioScheduler, uiScheduler);
}
}
My Application class:
public class AbsApplication extends Application {
private ObjectGraph graph;
#Override
public void onCreate() {
super.onCreate();
graph = ObjectGraph.create(getModules());
}
public Object[] getModules() {
return new Object[]{
new ApplicationModule(this),
new ApiModule(),
new AuthModule()
};
}
public void inject(Object object) {
graph.inject(object);
}
}
The question is - where do I instantiate (#Inject) the Authenticator? I don't use it directly in any of my classes. Can it be a field in the AbsApplication class? Should I even use Dagger for the Authenticator? Am I not using Dagger's modules properly?
I know that I can #Inject Authenticator inside the LoginFragment, but I am exploring new patterns. Bear with me, please.

Related

How can i inject my Retrofit DataService using Dagger2

In my MVP architecture i have Retrofit Instance
public class RetrofitInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/";
/**
* Create an instance of Retrofit object
* */
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
}
And DataService for it
public interface GetNoticeDataService {
#GET("weather?appid=0194877ecdcac230396a119c01d46100")
Observable<NoticeList> getNoticeData(#Query("lat") double lat , #Query("lon") double lon );
}
Also i have DataInteractor which is using RxJava Observable service to call api
public class GetNoticeIntractorImpl implements MainContract.GetNoticeIntractor {
private LatLng getloc(){
return currentLocation;
}
#SuppressLint("CheckResult")
#Override
public void getNoticeArrayList(final OnFinishedListener onFinishedListener) {
/** Create handle for the RetrofitInstance interface*/
GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Using RxJava Observable response to handle retrofit api*/
if(currentLocation!=null) {
service.getNoticeData(getloc().latitude, getloc().longitude)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> onFinishedListener.onFinished(items.getNoticeArrayList(), items.getMain(), items.getWind()), onFinishedListener::onFailure);
}
}
}
Here is presenter
public class MainPresenterImpl implements MainContract.presenter, MainContract.GetNoticeIntractor.OnFinishedListener {
private MainContract.MainView mainView;
private MainContract.GetNoticeIntractor getNoticeIntractor;
#Inject
public MainPresenterImpl(MainContract.MainView mainView, MainContract.GetNoticeIntractor getNoticeIntractor) {
this.mainView = mainView;
this.getNoticeIntractor = getNoticeIntractor;
}
#Override
public void onDestroy() {
mainView = null;
}
#Override
public void onRefreshButtonClick() {
if(mainView != null){
mainView.showProgress();
}
getNoticeIntractor.getNoticeArrayList(this);
}
#Override
public void requestDataFromServer() {
getNoticeIntractor.getNoticeArrayList(this);
}
#Override
public void onFinished(ArrayList<Notice> noticeArrayList, Main main, Wind wind) {
if(mainView != null){
mainView.setDataToRecyclerView(noticeArrayList,main,wind);
mainView.hideProgress();
}
}
#Override
public void onFailure(Throwable t) {
if(mainView != null){
mainView.onResponseFailure(t);
mainView.hideProgress();
}
}
}
And MainContract
public interface MainContract {
/**
* Call when user interact with the view and other when view OnDestroy()
* */
interface presenter{
void onDestroy();
void onRefreshButtonClick();
void requestDataFromServer();
}
/**
* showProgress() and hideProgress() would be used for displaying and hiding the progressBar
* while the setDataToRecyclerView and onResponseFailure is fetched from the GetNoticeInteractorImpl class
**/
interface MainView {
void showProgress();
void hideProgress();
void setDataToRecyclerView(ArrayList<Notice> noticeArrayList, Main main, Wind wind);
void onResponseFailure(Throwable throwable);
}
/**
* Intractors are classes built for fetching data from your database, web services, or any other data source.
**/
interface GetNoticeIntractor {
interface OnFinishedListener {
void onFinished(ArrayList<Notice> noticeArrayList, Main main, Wind wind);
void onFailure(Throwable t);
}
void getNoticeArrayList(OnFinishedListener onFinishedListener);
}
}
Adapter for MyActivity
public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.EmployeeViewHolder> {
private static Wind wind;
private static ArrayList<Notice> dataList;
private static Main main;
private Date currentTime = Calendar.getInstance().getTime();
public static String date;
private Context mContext;
private RecyclerItemClickListener recyclerItemClickListener;
public NoticeAdapter(ArrayList<Notice> dataList, Main main, Wind wind, RecyclerItemClickListener recyclerItemClickListener,Context context) {
NoticeAdapter.dataList = dataList;
NoticeAdapter.main = main;
NoticeAdapter.wind = wind;
this.recyclerItemClickListener = recyclerItemClickListener;
this.mContext=context;
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.single_view_row, parent, false);
return new EmployeeViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull EmployeeViewHolder holder, #SuppressLint("RecyclerView") final int position) {
setDate(currentTime.toString().substring(0,currentTime.toString().length()-18));
if(getAddressMap()!=null){holder.txtNoticeAddress.setText("Loc: "+getAddressMap());}else{holder.txtNoticeAddress.setText("Loc: Unknown location");}
holder.imageIcon.setImageURI(Uri.parse("android.resource://com.locweather/drawable/i"+dataList.get(position).getIcon()));
holder.txtNoticeWind.setText("Wind: "+roundUp(+wind.getSpeed())+"m/s, "+arrow());
holder.txtNoticeTempMain.setText(roundUp(+main.getTemp())+"°C");
holder.txtNoticeWeather.setText(dataList.get(position).getWeather()+" : "+dataList.get(position).getInfo());
holder.txtNoticeTemp.setText("Feels: "+roundUp(+main.getFeelsLike())+"°C ");
holder.txtNoticeTime.setText(date);
holder.txtNoticeHumidity.setText("Humidity: "+main.getHumidity()+"%");
holder.txtNoticePressure.setText("Pressure: "+main.getPressure()+"hPa");
holder.itemView.setOnClickListener(v -> {
recyclerItemClickListener.onItemClick();
saveNoticeList(mContext,dataList); });
holder.saveButton.setOnClickListener(v -> {
recyclerItemClickListener.onItemClick();
saveNoticeList(mContext,dataList); });
}
private static String getAddressMap() {
return MapsActivity.addressMap;
}
private static void setDate(String date) {
NoticeAdapter.date = date;
}
#Override
public int getItemCount() {
return dataList.size();
}
private static LatLng getloc(){
return currentLocation;
}
class EmployeeViewHolder extends RecyclerView.ViewHolder {
ImageView imageIcon;
Button saveButton;
TextView txtNoticeWeather, txtNoticeTempMain,txtNoticeTemp, txtNoticeHumidity,txtNoticeAddress,txtNoticePressure,txtNoticeWind,txtNoticeTime;
EmployeeViewHolder(View itemView) {
super(itemView);
saveButton=itemView.findViewById(R.id.save_button);
imageIcon=itemView.findViewById(R.id.image_icon);
txtNoticeTime= itemView.findViewById(R.id.txt_time);
txtNoticeWind= itemView.findViewById(R.id.txt_notice_wind);
txtNoticeAddress= itemView.findViewById(R.id.txt_notice_title);
txtNoticeWeather = itemView.findViewById(R.id.txt_notice_weather);
txtNoticeTemp = itemView.findViewById(R.id.txt_notice_temp);
txtNoticeHumidity = itemView.findViewById(R.id.txt_notice_humidity);
txtNoticePressure = itemView.findViewById(R.id.txt_notice_pressure);
txtNoticeTempMain = itemView.findViewById(R.id.txt_notice_temp_main);
}
}
private static void saveNoticeList(Context context, List<Notice> noticeList) {
if (context != null && noticeList != null) {
WeatherData weatherData = new WeatherData(getAddressMap(), wind.getSpeed(), wind.getDeg(), dataList.get(0).getIcon(), dataList.get(0).getInfo(), dataList.get(0).getWeather(), main.getTemp(), main.getFeelsLike(), main.getHumidity(), main.getPressure(), date, getloc().latitude, getloc().longitude);
WeatherDatabase.getInstance(context)
.weatherDao()
.save(weatherData);
}
}
How can i inject this DataService to my Interactor by using Dagger2? Should i use Singleton or Component or something else?
I'll be glad of any kind of help.
I'll assume you want to keep your RetrofitInstance singleton available for now, at least until you have migrated all Retrofit uses to Dagger 2.
In order to inject an interface, or a class whose constructor you don't control, you need to use a Module. This tells Dagger how to create instances of that class or interface given some dependencies:
#Module
public class WebServiceModule {
#Singleton
#Provides
Retrofit provideRetrofit() {
// This method tells Dagger all it needs to know about creating
// a Retrofit instance. This will be replaced by something closer
// to BWappsandmore's answer after RetrofitInstance is no longer needed.
return RetrofitInstance.getRetrofitInstance();
}
#Singleton
#Provides
GetNoticeDataService provideGetNoticeDataService(Retrofit retrofit) {
return retrofit.create(GetNoticeDataService.class);
}
This module can then be included in your Component, which will in turn create any objects it knows how to create, either from modules, #BindsInstance values passed into your component factory method, or classes with #Inject constructors. Since you control your interactor's constructor, you can simply annotate it with #Inject:
// #Reusable or #Singleton if you only need one interactor of this type.
public class GetNoticeInteractorImpl implements MainContract.GetNoticeInteractor {
private GetNoticeDataService service
#Inject
GetNoticeInteractorImpl(GetNoticeDataService service) {
this.service = service;
}
private LatLng getloc(){
return currentLocation;
}
#SuppressLint("CheckResult")
#Override
public void getNoticeArrayList(final OnFinishedListener onFinishedListener) {
// Our service was injected in the constructor, so there
// is no need to create it here.
// You might also consider injecting your schedulers in the future
// for unit testing.
if(currentLocation!=null) {
service.getNoticeData(getloc().latitude, getloc().longitude)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> onFinishedListener.onFinished(items.getNoticeArrayList(), items.getMain(), items.getWind()), onFinishedListener::onFailure);
}
}
}
#Module
abstract class AnotherModule { // or interface
#Binds
abstract MainContract.GetNoticeInteractor bindGetNoticeInteractor(GetNoticeInteractorImpl implementation);
}
Of course, this is useless if you can't ultimately access your interactor. Since you don't even create your Activity classes, you need to request injection from a Component. In Android apps, this is typically created within the Application object in onCreate().
#Component(modules = {WebServicesModule.class, AnotherModule.class})
#Singleton
public interface AppComponent {
#Component.Factory
interface Factory {
AppComponent create(#BindsInstance Application application); // or whatever
}
void bindMainActivity(MainActivity activity);
}
// Probably not a singleton, but if you create an activity scope later, this might use that scope.
class MainPresenter {
#Inject
public MainPresenter(MainContract.GetNoticeInteractor interactor) {
this.getNoticeInteractor = interactor
}
// ...
}
class MainActivity {
#Inject
MainPresenter presenter;
#Override
public void onCreate(Bundle savedInstanceState) {
somehowGetComponent().inject(this);
super(savedInstanceState);
// ...
}
// ...
}
Now, since your MainActivity requires a MainPresenter, Dagger will create one for you when you request injection. This in turn requires a GetNoticeInteractor, which requires GetNoticeInteractorImpl, and so forth, and Dagger will take care of all of this behind the scenes.
If your presenter's constructor requires other arguments (such as a View), it might be simpler for now for MainActivity to request injection directly into the presenter. Ultimately, you will want all of your inject(SomeClass target) methods to refer to Activities, Services, and such, since there is no other way to inject those until your minSdkVersion is 28 or higher.
#Module
object WebServiceModule {
#Singleton
#Provides
fun providesGetNoticeDataService(retrofit: Retrofit): GetNoticeDataService =
retrofit.create<GetNoticeDataService>(GetNoticeDataService::class.java)
#Provides
fun providesGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create()
#Provides
fun providesOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build()
#Provides
fun providesOkHttpLoggingInterceptor(): HttpLoggingInterceptor =
HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
#Provides
fun provideRxJava2CallAdapterFactory(): RxJava2CallAdapterFactory =
RxJava2CallAdapterFactory.create()
#Provides
fun providesRetrofit(
client: OkHttpClient,
converterFactory: GsonConverterFactory,
adapterFactory: RxJava2CallAdapterFactory
): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(adapterFactory)
.client(client)
.build()
}

Unit test using Mockito- Make mock of Abstract, void method

I am trying MVP pattern with TDD.
I have the following contract for Model, View And Presenter
Contract Class
interface GithubContract {
interface View {
void displayUsers(List<GurkhaComboDTO> userList);
}
interface Model {
void getUsersAndPromptPresenter(String userName, Presenter presenter);
}
interface Presenter {
void searchUsers(String userName);
void loadUsers(List<GithubUserDTO> userList);
}
}
I am trying to unit test the presenter logic like this :
Test Class
#RunWith(MockitoJUnitRunner.class)
public class GithubPresenterWithMockitoTest {
#Mock
GithubContract.Model mockedModel;
#Test
public void shouldDisplayUsersToScreen() {
//given
final GithubContract.View view = new MockView(); // I have created the mock myself for the view this time.
final GithubContract.Presenter presenter = new GithubPresenter(view, mockedModel);
***********************************************************
// I do not know what to write here
****************************************************
presenter.searchUsers("");
Assert.assertEquals(true, ((MockView) (view)).enoughItems);
}
}
My MockView / VIEW class looks like this :
This is -> Mock class
class MockView implements GithubContract.View {
boolean enoughItems = false;
#Override
public void displayUsers(List<GurkhaComboDTO> userList) {
enoughItems = true;
}
}
My PRESENTER implementation of contract is like this ..
This is -> Real Class
class GithubPresenter implements GithubContract.Presenter {
private GithubContract.View view;
private GithubContract.Model model;
GithubPresenter(GithubContract.View view, GithubContract.Model model) {
this.view = view;
this.model = model;
}
#Override
public void searchUsers(String userName) {
model.getUsersAndPromptPresenter(userName, this);
}
#Override
public void loadUsers(List<GithubUserDTO> data) {
if (data != null) {
if (!data.isEmpty()) {
view.displayUsers(users);
}
}
}
I have the MODEL class Implementation like this :
This is -> Real Class
public class GithubModel implements Model {
#Inject
GithubAPIService apiService;
private Call<GithubUserListDTO> userListCall;
private Context context;
GithubModel(Context context) {
this.context = context;
apiService = Util.getAPIService(); // I am using dagger, retrofit and okhttp3 with GSON to get Objects directly from network call
}
#Override
public void getUsersAndPromptPresenter(final String userName, final GithubContract.Presenter presenter) {
userListCall = apiService.searchGitHubUsers(userName);
if(Util.isInternetConnected(context)) {
userListCall.enqueue(new Callback<GithubUserListDTO>() {
#Override
public void onResponse(Call<GithubUserListDTO> call, Response<GithubUserListDTO> response) {
try {
presenter.loadUsers(response.body().getList());
} catch (Exception ignored) {
Util.log(ignored.getMessage());
}
}
#Override
public void onFailure(Call<GithubUserListDTO> call, Throwable t) {
}
});
}else {
Util.log("No Internet");
}
}
}
Now the real problem part:
I was successfully able to test the presenter with the mock of GithubContract.Model myself, But I want to use Mockito to mock the Model but as my getUsersAndPromptPresenter() method is abstract, returns void, takes parameters and calls back to presenter from an Inner class inside the method.
How can I mock my Model? If I need to bring some change in architecture in order to be able to make it testable, then please suggest it.
You shouldn't pass presenter to Model, Model and Presenter shouldn't be tightly coupled because it prevents model classes from being reusable. Instead provide succesfull and error callbacks(or a composite object that contains both these callbacks). And then you will be able to capture that callback with mockito and call the required one. Also it's very common today to use RxJava, it makes it easier to mock Model classes.
And here is a general good practice: you should avoid to use And/Or words in method names because it indicates that the method is doing more than one thing which is bad

Dagger2 singleton annotation not working

So, a bit of context. I'm using Dagger2, Retrofit and RxAndroid and structuring my app using an MVP architecture.
For now, all I'm doing is making a network request to the API a retrieving some information as soon as my main activity starts. I'm trying to persist my presenters through configuration changes to avoid making a new http request every time I rotate my screen.
MainActivity.java
public class MainActivity extends AppCompatActivity implements ForecastView {
#Inject
Presenter forecastPresenter;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.weather);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initializeDependencies();
initializePresenter();
}
private void initializeDependencies() {
DaggerWeatherApiComponent.builder()
.build().inject(this);
}
private void initializePresenter() {
forecastPresenter.attachView(this);
forecastPresenter.onCreate();
}
WeatherApiComponent.java
#Component(modules = {EndpointsModule.class})
#Singleton
public interface WeatherApiComponent {
void inject(MainActivity context);
}
EndpointsModule.java
#Module #Singleton
public class EndpointsModule {
#Provides
#Singleton
WeatherEndpoints provideEndpoints() {
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.baseUrl("http://api.openweathermap.org/data/2.5/")
.build();
return retrofit.create(WeatherEndpoints.class);
}
#Provides
#Singleton
Repository providesRepository(RestRepository repository) {
return repository;
}
#Provides
#Singleton
Presenter providesPresenter(ForecastPresenter presenter) {
return presenter;
}
}
RestRespository
public class RestRepository implements Repository {
private WeatherEndpoints endpoints;
static final String API_KEY = "xxxxxxxxxxxxxxxxxxxxx";
#Inject
public RestRepository(WeatherEndpoints endpoints) {
this.endpoints = endpoints;
}
public Observable<Current> getCurrentWeather(String cityName) {
return endpoints.getCurrent(cityName, API_KEY);
}
public Observable<com.feresr.rxweather.models.List> getForecast(String cityName) {
return endpoints.getForecast(cityName, API_KEY).flatMap(new Func1<FiveDays, Observable<com.feresr.rxweather.models.List>>() {
#Override
public Observable<com.feresr.rxweather.models.List> call(FiveDays fiveDays) {
return Observable.from(fiveDays.getList());
}
});
}
}
ForecastPresenter.java
public class ForecastPresenter implements Presenter {
private GetForecastUseCase useCase;
private Subscription forecastSubscription;
private ArrayList<List> lists;
private ForecastView forecastView;
#Inject
public ForecastPresenter(GetForecastUseCase forecastUseCase) {
this.useCase = forecastUseCase;
lists = new ArrayList<>();
}
#Override
public void onStop() {
if (forecastSubscription.isUnsubscribed()) {
forecastSubscription.unsubscribe();
}
}
#Override
public void attachView(View v) {
forecastView = (ForecastView) v;
}
#Override
public void onCreate() {
if (lists.isEmpty()) {
forecastSubscription = useCase.execute().subscribe(new Action1<List>() {
#Override
public void call(List list) {
lists.add(list);
forecastView.addForecast(list.getWeather().get(0).getMain());
}
});
} else {
forecastView.addForecast(lists.get(0).toString());
}
}
The constructor on this class (presenter) keeps calling itself as I rotate my Acitivity. I've annotated with #Singleton most of my classes. I don't know what else to do.
EDIT: Note that I haven't gotten into dagger SCOPES just yet, for now I don't care if this singleton presenter lives as long as my app. I'll fix that later.
It looks like you're recreating the Dagger component every time MainActivity.onCreate(Bundle) is called, and the activity is reinstantiated when you rotate the screen.
Like other scopes, #Singleton means there will be one instance of the object for the lifetime of the component, not for the lifetime of the JVM. You typically have to make sure there is only one instance of the #Singleton component yourself, usually by keeping it in a field in your Application.
You create a new dagger component every time here:
private void initializeDependencies() {
DaggerWeatherApiComponent.builder()
.build().inject(this);
}
A scoped dependency exists as ONE instance PER component.
If you create a new component, it will have its own scope, and it will create its own instance.
You should either invest in Mortar scopes to preserve your component, or you should have some sort of "cache" in your Application instance.

Android IOC Dagger Framework - How to inject a nested field ?

I'm using Dagger for Android for dependency injections.
I have a UserService object in a Main Class:
public class Main implements Runnable {
#Inject
UserService service;
#Override
public void run() {
for (User f : service.getUserByName("toto")) {
System.out.print(f.getM_Nom());
}
}
public static void main(String[] args) {
ObjectGraph objectGraph = ObjectGraph.create(new UserModule());
Main m = objectGraph.get(Main.class);
m.run();
}
}
I managed to inject the "service" field and to call the method "getUserByName("")".
But in my "UserService", I have an other custom object ("RepositoryUser" class):
public class UserService implements IUserService {
#Inject
RepositoryUser m_Repository;
#Override
public List<User> getUserByName(String name) {
return m_Repository.getAll();
}
}
My problem is that this field is not inject: the "m_Repository" field is null and I get a null pointer exception when I try to use my RepositoryUser object.
Here is my Provider:
#Module(
injects = {UserService.class, Main.class, RepositoryUser.class}
)
public class UserModule {
#Provides
RepositoryUser provideRepositoryUser() {
return new RepositoryUser();
}
#Provides
UserService provideUserService() {
return new UserService();
}
}
Any idea ?
Thanks in advance !
It is preferrable to use Constructor Injection in this case. This can be achieved as follows:
Main:
public class Main implements Runnable {
private final IUserService service;
#Inject
public Main(IUserService service) {
this.service = service;
}
#Override
public void run() {
for (User f : service.getUserByName("toto")) {
System.out.print(f.getM_Nom());
}
}
public static void main(String[] args) {
ObjectGraph objectGraph = ObjectGraph.create(new UserModule());
Main m = objectGraph.get(Main.class);
m.run();
}
}
UserService:
public class UserService implements IUserService {
private final RepositoryUser m_Repository;
#Inject
public UserService(RepositoryUser repository) {
m_Repository = repository;
}
#Override
public List<User> getUserByName(String name) {
return m_Repository.getAll();
}
}
RepositoryUser:
public class RepositoryUser {
#Inject
public RepositoryUser() {
}
/* ... */
}
UserModule:
#Module(injects = Main.class)
public class UserModule {
#Provides
IUserService provideIUserService(UserService userService){
return userService;
}
}
Everywhere the #Inject annotation is present on a constructor, Dagger can automatically create an instance of that item. So when you request a RepositoryUser instance in the UserService constructor, Dagger will see the #Inject annotation on RepositoryUser's constructor, and use that to create a new instance. We do not need an #Provides method here.
The IUserService parameter on the Main constructor cannot be instantiated, since it is an interface. Using the provideIUserService method in the module, we tell Dagger that we want it to create a new UserService instance.
We do have an #Inject annotation on the Main constructor, but we request it using ObjectGraph.get(Class<T> clzz). Therefore, we need to add injects = Main.class to our module.

Implementing OAuth2 with AccountManager, Retrofit and Dagger

I'm trying to figure out what would be the best way to implement a Retrofit client which supports AccountManager.getAuthToken() for OAuth2 flow.
I'm following the U2020
Ideally I would like to have a simple injector along these lines
public class ExampleFragment extends InjectionFragment {
#Inject ApiDatabase database;
#Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
subscribe(database.getSomeData(), ...);
}
}
I'm considering a RequestInterceptor similar to the example
public final class ApiHeaders implements RequestInterceptor {
ApiKeyProvider apiKeyProvider;
#Inject
public ApiHeaders(ApiKeyProvider apiKeyProvider) {
this.apiKeyProvider = apiKeyProvider;
}
#Override
public void intercept(RequestFacade request) {
// How to handle exceptions from getAuthToken?
request.addHeader("Authorization", "Bearer " + apiKeyProvider.getAuthKey());
}
}
and
public class ApiKeyProvider {
AccountManager accountManager;
Activity activity;
public ApiKeyProvider(Activity activity, AccountManager accountManager) {
this.activity = activity;
this.accountManager = accountManager;
}
public String getAuthKey() throws AccountsException, IOException {
AccountManagerFuture accountManagerFuture = accountManager.getAuthTokenByFeatures(ACCOUNT_TYPE,
AUTHTOKEN_TYPE, new String[0], activity, null, null, null, null);
return accountManagerFuture.getResult().getString(KEY_AUTHTOKEN);
}
}
I'm not sure how to inject the ApiKeyProvider into the ApiHeaders class as it depends on an "ActivityModule" (lower down the dagger DAG graph).
Also not sure how to handle exceptions.
Can anyone provide a full working example?
This ended up being a little lengthy.
This GIST hopefully encompasses all the relevant files

Categories

Resources