Koin: Need dynamic add/remove scope definition

Created on 11 Jan 2019  路  4Comments  路  Source: InsertKoinIO/koin

As android developer, using scope feature in activity and fragment.

  • Many instance of activity or fragment created during application run
  • When use MVP, where Activity is View and Presenter is inject by using scope
    --> So that koin provide one presenter instant for many view (activity) because of same scope
    --> We need dynamic add scope definition with dynamic unique id or name

--> So solution may be:

  • dynamic add remove scope
  • or func to remove instant from koin holder

Sorry my bad English

question

Most helpful comment

@arnaudgiuliani
thank for your support. I understands, I'll try as your answer.

All 4 comments

try with Koin 2.0 Scope API

@arnaudgiuliani
I've read scope api of koin 2.0. But I can't see the way how to create and use dynamic add/remove scope definition. All scope must be pre-define as startKoin but not programmatic by code.
For ex:

  • I want ViewPager has 3 pages which each one is same Fragment A.
  • If I use scope api, I got only 1 instance instead of 3 with different scope name. What I want is

    • Presenter$1 for scope name "Fragment A_0",

    • Presenter$2 for scope name "Fragment A_1",

    • Presenter$3 for scope name "Fragment A_2",

      But I got:

    • Presenter$00 for scope name "Fragment A" for 3 page.

Could you pls tell me how to do this in koin 2.0?

You have several ways to define a scope. A scope is a space where you will have a scoped definition.

You can create a scope with the scope function, to gather scoped definitions. Any scoped definition outside of this scope can be injected.

You can also base yourself on Android scopes (Activity, Fragment) to have scopes based on lifecycle components.

A scope instance is an instance of a scope.

In your case, use the getFragmentScope() in your fragment to inject your scoped definition.

module {
    scope<MyFragment>{
        scoped { MyPresenter() }
    }
}

On each MyFragment instance, you will use val presenter MyPresenter : getFragmentScope().inject() or .get() to retrieve your MyPresenter instance for current scope.
Then you will have 1 instance of MyPresenter by instance of MyFragment.

Else use simply a factory to define your presenter. it will do the same in this simple case.

@arnaudgiuliani
thank for your support. I understands, I'll try as your answer.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pchmielowski picture pchmielowski  路  3Comments

haroldadmin picture haroldadmin  路  3Comments

dakuenjery picture dakuenjery  路  4Comments

caleb-allen picture caleb-allen  路  4Comments

sankarsana picture sankarsana  路  4Comments