Dagger + Otto建筑指导

时间:2014-11-17 15:53:13

标签: android architecture dagger otto

我正在尝试开发一个采用模块化架构的应用程序(没有人知道没有人,但每个人仍然可以沟通)。我将从一个例子开始:

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
}

Authenticator 捕获此事件,然后回发:

@Subscribe
public void onAuthorizeEvent(AuthorizeEvent event) {
    // ... login
    bus.post(new AuthEvent(user));
}

Authenticator取决于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);
}

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

我的Application课程:

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

问题是 - 我在哪里实例化@Inject Authenticator?我不会在我的任何课程中直接使用它。它可以是AbsApplication类中的字段吗?我应该在Authenticator使用Dagger吗?我没有正确使用Dagger的模块吗?


我知道我可以在@Inject AuthenticatorLoginFragment,但我正在探索新的模式。请跟我说。

0 个答案:

没有答案