Question

Jake Wharton's talk at Devoxx 2013, Architecting Android Applications with Dagger, talked about creating a Dagger scope for logged in users only. This sort of thing sounds really clean, and I want to do this in my applications.

The code that was discussed in the talk was something along the lines of:

public class LoggedInActivity extends Activity {

    @Inject User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logged_in);

        DaggerScopesApp app = (DaggerScopesApp) getApplication();
        app.getObjectGraph().plus(new UserModule("exampleusername")).inject(this);

        findViewById(R.id.do_something_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(LoggedInActivity.this, user.username + " : " +
                        user.someValue++, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

However, if the injected User is scoped as a @Singleton, then its properties will disappear on config change (as the object graph is created in onCreate).

The solution is pretty simple, you can just do this "plus" operation once and store the new object graph somewhere else (maybe the application class), but I was wondering if this is a good approach? Can anyone from Square provide any insight into what you do in your applications? Do you just not have singleton objects in the "logged-in" graph?

Was it helpful?

Solution

The solution is pretty simple, you can just do this "plus" operation once and store the new object graph somewhere else (maybe the application class), but I was wondering if this is a good approach?

Yep. The logged-in graph's lifecycle needs to live as long as the user is logged in and the process is around. Since the activity's lifecycle is extremely short, this isn't a good place for it.

I used it as an example to ease people into the concept using something they are familiar with.

Can anyone from Square can provide any insight into what you do in your applications?

All graphs that aren't tied to UI are managed by an Application class. Through this we are guaranteed that it's created once, created first, and only disappears if the process dies.

Anything UI-related (activity-scope graphs, fragment-scope graphs, etc.) is plussed on top of these as the UI comes and goes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top