-1

I have a project that currently supports MVP and MVVM. Coroutines, hilt, repository pattern are also used. I need single resources that I will cache.

For example, activity A executes a network request, the user can go to activity B during the execution of the request. However, I need that, regardless of whether I left activity A or not, the network request continues its execution and cache data.

I have a repository that contains the logic for executing a request and caching it. I also tried to provide the repository with the @Singleton annotation using the hilt.

However, as soon as I switch from activity A to activity B, the network request stops executing and no data is stored in the cache.

I understand that what I have done is not sufficient to make the network request be executed in the background even if I leave the activity, but unfortunately I do not understand how I can implement this.

I also read that it is possible to use the same repository instance in the view models of activity A and activity B. But what if it is possible to switch from activity A to many other activities, then I should use the repository instance in the view models of all activities? In addition, my problem is that one activity can have a view model, and another presenter, because. still not the whole project migrated to MVVM.

I tried to find some information on the Internet, but I did not find anything like it.

Please help me. Perhaps someone can share interesting sources with a similar implementation.

testivanivan
  • 967
  • 13
  • 36

1 Answers1

1

Use GlobalScope coroutine to make the request last as long as the Application but you can also use workmanager to make the request and cache it.

For GlobalScope refer to: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/

For WorkManager refer to: https://developer.android.com/topic/libraries/architecture/workmanager

Anurag Singh
  • 156
  • 2
  • 14