4

I try to create scope for a feature. I define a module like this.

val appModule = module {
    scope(named("ARTIST_SCOPE")) {
        scoped {
            ArtistRepository(get())
        }
        scoped {
            GetArtistsUseCase(get())
        }
        viewModel { ArtistViewModel(get()) }
    }
}

My goal is to make ArtistRepository, GetArtistUseCase, and ArtistViewModel only accessible inside Artist Feature.

In my activity

class ArtistActivity : AppCompatActivity() {

    private val artistScope = getKoin().createScope("artistScope", named("ARTIST_SCOPE"))
    private val viewModel: ArtistViewModel by artistScope.viewModel(this)
...
}

My problem is when I leave this activity and return back to it.

I got this error.

org.koin.core.error.ScopeAlreadyCreatedException: A scope with id 'artistScope' already exists. Reuse or close it.
enter code here

How to reuse the existing scope? or Am I implement the scope in the right way?

Boonya Kitpitak
  • 3,607
  • 1
  • 30
  • 30

1 Answers1

3

You want to use getOrCreateScope(). This will get an existing instance if you have one that isn't closed with the same scopeId, or it will create a new instance if it needs to.

Mark
  • 2,362
  • 18
  • 34