Android-CleanArchitecture icon indicating copy to clipboard operation
Android-CleanArchitecture copied to clipboard

Multiple component provided by Activity

Open Shyri opened this issue 10 years ago • 1 comments

The current implementation allows an Activity to provide a component to any subclass implementing HasComponent<C> interface. For instance UserListFragment.java

private void initialize() {
    this.getComponent(UserComponent.class).inject(this);
    this.userListPresenter.setView(this);
}

But what about further fragments inside the same Activity. Imagine I want to add some OtherFragment.java later in the same Activity, which needs some OtherComponent. As the Activity can implement HasComponent<C> for only one type it cannot provide OtherComponent to the new Fragment.

I'm new to android-clean-architecture and maybe I'm missing something. Maybe this is not the propper way to achieve what I want, any advice?

Thanks!

Shyri avatar Jan 08 '16 09:01 Shyri

public class MainActivity extends AppCompatActivity {

    private UserComponent userComponent;
    private OtherComponent otherComponent;

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

        // Initialize components
        AppComponent appComponent = ((MyApplication) getApplication()).getAppComponent();
        userComponent = appComponent.userComponent(new UserModule());
        otherComponent = appComponent.otherComponent(new OtherModule());

        // Inject into fragments
        if (savedInstanceState == null) {
            UserListFragment userListFragment = new UserListFragment();
            OtherFragment otherFragment = new OtherFragment();

            userComponent.inject(userListFragment);
            otherComponent.inject(otherFragment);

            getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, userListFragment)
                .add(R.id.fragment_container, otherFragment)
                .commit();
        }
    }

    public UserComponent getUserComponent() {
        return userComponent;
    }

    public OtherComponent getOtherComponent() {
        return otherComponent;
    }
}

ljluestc avatar Sep 08 '24 21:09 ljluestc