0

I have a repository where a chain of network requests is calling. The repository is accessed from the interactor. And interactor is accessed from viewModel. The view model is attached to activity A. If I go to activity B, which has its own viewModel, then the request chain in the repository of activity A does not complete its execution.

Is it possible to make a repository whose life cycle will be equal to the life cycle of the application. I need all requests to complete even if I go to a new activity.

Please, help me.

testivanivan
  • 967
  • 13
  • 36

2 Answers2

1

This is covered in the Coroutines guide on developer.android.com

class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
    private val externalScope: CoroutineScope,
    private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    // As we want to complete bookmarking the article even if the user moves
    // away from the screen, the work is done creating a new coroutine
    // from an external scope
    suspend fun bookmarkArticle(article: Article) {
        externalScope.launch(defaultDispatcher) {
            articlesDataSource.bookmarkArticle(article)
        }
            .join() // Wait for the coroutine to complete
    }
}

Here externalScope is defined like this (for a scope with application lifetime):

class MyApplication : Application() {
  // No need to cancel this scope as it'll be torn down with the process
  val applicationScope = CoroutineScope(SupervisorJob() + otherConfig)
}
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56
-1

You should create a singleton Repository class, then access its instance anywhere you want.

object Repository {
    val instance: Repository
        get() {
            return this
        }
}

You can create create its object in ViewModel for A and create object in ViewModel for B. Both will have same instance for Repository class, so in this way you can achieve what you need.

Ali Ahmed
  • 2,130
  • 1
  • 13
  • 19