简体   繁体   中英

Android Jetpack: lifecycle-aware recurrent periodic task execution with LiveData and ViewModels

My app already uses some recent Android patterns for network calls:

  • LiveData class
  • MVVM architecture with ViewModel class
  • Kotlin coroutines for Repository classes
  • Retrofit interface etc.

Now I want to implement common feature which is automatic fetching current data from API every few minutes .

I read about WorkManager and give it a shot - I implemented it but I then saw that WorkManager ( JobScheduler ) keeps running after closing app which is not what I want. I also felt like WorkManager API is too much overkill for that simple task.

Then I read a guide on Codepath that suggests Handler class for main thread repetitive jobs and ScheduledThreadPoolExecutor for background repetitive tasks. I know that they will probably work fine but I'm not sure if they are best solution.

My question is: what's currently the best way for recurrent API calls that:

  • works with LiveData and ViewModel classes (observable result like normal API call)
  • is Kotlin-friendly (any way to make coroutine recurrent?)
  • is "lifecycle-aware", meaning that it will stop when app goes to the background?

WorkManager is for guaranteed works that needs to be executed even if your app exit or the device is restarted. From your description this doesn't seem your use case.

A threadpool seems the best option in this case, but you can judge yourself starting from this guide: " Background Tasks ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM