Best API to do background task in android? - android

Which is fastest Kotlin Coroutines or Work Manager API to fetch images and videos from an Android phone. Or any other Methods ?

Coroutines are designed to provide a lightweight asynchronous programming framework. You can use Coroutines to start async job which is bounded to the local lifecycle scope of some part of your app. For example, if you want to call a REST API when the user clicks the "login" button. In this case, you don't really care if this result was complete (for example the user can go back and the task will cancel). If you need to be sure the task will complete then the WorkManager would be a better choice (e.g. it would be suitable for a long-running upload task which would be better to perform in the background).
If you'd like to see more about the practical use of coroutines for async jobs on Android I can recommend my article:
https://www.netguru.com/codestories/android-coroutines-%EF%B8%8Fin-2020

Related

Network call when exiting the screen - Android coroutines

I am trying to implement a UI in a fragment, where user can make all sorts of updates and I need send it over to backend when user EXITS the screen. (Batch update)
I am using MVVM pattern, where network calls are performed from viewmodel . Now, viewModelScope.launch won't work here, since as soon as user exits, the coroutine is canceled by onCleared().
For now, I added GlobalScope and it works but I have also come across this and this question
Are there any other alternatives to accomplish this with Coroutines?
Coroutines are mostly recommended for work that should start immediately and is scoped to the lifecycle of a Fragment, Activity, ViewModel or any other object with a lifecycle. Since the rest of the coroutine builders are tied to scopes, they wont accomplish what you are trying to do, since the user might leave your app at any given time.
A better approach would be using WorkManager with CoroutineWorker, which isn't tied to your UIs or App lifespan and still takes the advantages of working with Coroutines. With WorkManager, your work could be enqueued when the user leaves your designated screen and will be guaranteed to run once the constraints you specify are fulfilled (for example having internet connection). I recommend you to check Android's Guide to background processing if you are still making up your mind on which solution to use.

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".

can I always use WorkManager instead of coroutines?

I wonder why should I bother with rx or coroutines when there is brilliant solution as WorkManager. But for almost all tutorials they use coroutines so may be WorkManager has disadvantages ?
The scope of both is different. WorkManager is to schedule deferrable (for any later time) or immediately.
tasks asynchronously.
As documentation says
The WorkManager API makes it easy to specify deferrable, asynchronous
tasks and when they should run. These APIs let you create a task and
hand it off to WorkManager to run immediately or at an appropriate
time.
On the other hand, coroutines are designed to compute a given task only immediately and asynchronously.
Also
Internally, coroutines and WorkManager work differently. Work manager heavily depends on Android system components like Services, Alarm manager, etc to schedule the work whereas coroutines schedule the work on Worker Threads and also is a language feature unlike WorkManager (API). So it is safe to say that coroutines do not go beyond your application. On the other hand, WorkManager can even execute the given tasks when your application is not active. for instance, background services.
Also as Marko answered, using coroutines will lead to better code readability and quality due to their fundamental design.
I would also like to include ANKO, Its a great library that provides a helpful API around coroutines for Android.
Background tasks fall into one of the following main categories:
Immediate
Deferred
Exact
To categorize a task, answer the following questions:
Does the task need to complete while the user is interacting with the application?
If so, this task should be categorized for immediate execution. If
not, proceed to the second question.
Does the task need to run at an exact time?
If you do need to run a task at an exact time, categorize the task as
exact.
Most tasks don't need to be run at an exact time. Tasks generally allow for slight variations in when they run that are based on conditions such as network availability and remaining battery. Tasks that don't need to be run at an exact time should be categorized as deferred.
Use Kotlin Coroutine when a task needs to execute immediately and if the task will end when the user leaves a certain scope or finishes an interaction.
Use WorkManager when a task needs to execute immediately and need continued processing, even if the user puts the application in the background or the device restarts
Use AlarmManager when a task that needs to be executed at an exact point in time
For more details, visit this link
If your goal is writing clean code without explicitly constructed callbacks you pass to background tasks, then you'll find that coroutines are the only option.
Using coroutines by no means precludes using WorkManager or any other tool for background operations of your choosing. You can adapt the coroutines to any API that provides callbacks as a means to continue the execution with the results of background operations.
From official Documentation:
It is important to note that coroutines is a concurrency framework, whereas WorkManager is a library for persistent work.
WorkManager:
Support for both asynchronous one-off and periodic tasks
Support for constraints such as network conditions, storage space, and charging status
Chaining of complex work requests, including running work in parallel
Output from one work request used as input for the next
Handles API level compatibility back to API level 14(see note)
Works with or without Google Play services
Follows system health best practices
LiveData support to easily display work request state in UI
Waits proper time to run.
Coroutines:
Clean code, works under the hood in a different way. Run immediately.
So depending on your requirements choose the better option.
Has others replied, WorkManager solves a different problem than Kotlin's corountines or a reactive library like RxJava.
WorkManager is now available as beta and additional documentation is produced that hopefully makes this clear.
One of these documents is the blog post I worte with some colleagues: Introducing WorkManager, where you can read:
A common confusion about WorkManager is that it’s for tasks that needs to be run in a “background” thread but don’t need to survive process death. This is not the case. There are other solutions for this use case like Kotlin’s coroutines, ThreadPools, or libraries like RxJava. You can find more information about this use case in the guide to background processing.

Do I ALWAYS need to use AsyncTask when using MySQL?

Hi guys I have a question about Asyntask which is used in android studio :
As far as I know AynTask is used for user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished.
But let's say that I want to register an account so that I can login, that shouldnt take time at all so why should I use Asyntask for this?
Let's say I want to send 100 strings to the Database, that can be done in milisecs I think, so again, why to use and how to decide when to use Asyntask?
I hope you guys can help me out, I have been searching for a long time !
If you don't know how much time operation will take, you should perform it in a separate thread and then pass the results to UI thread. I think the database should be accessed in a separate thread as well as HTTP requests. In the case of time-consuming query, it may be a long operation. AsyncTask is one way to do it. You can also use other techniques. The popular technique used nowadays is applying RxJava library, which gives you the high-level functional reactive interface for writing multi-threaded applications with a few additional features. You can perform an operation in e.g. Sechdulers.io() (I/O) thread and then pass the result to AndroidSchedulers.mainThread(), which is UI thread.
There are also other techniques like using Looper & Handler from Android SDK or using Thread class from Java, but such techniques require more knowledge, more work, writing more boilerplate code & you have more problems to deal with.

Designing a "task" layer between client and network that organizes the synchronous network/api calls

For the app i'm working on, we have bunch of api calls that accomplish certain things. Usually each thing takes more than one api call. What i want to design is a middle layer where the UI/Client can just say do a certain task, middle layer would invoke that task, and task would handle all the api call sequence..
I'm having a hard time picking the right design patterns. Basically i was thinking a mediator type pattern that mediates interactions between UI, network and tasks. And everything would only talk to mediator, but then this might make the mediator too complicated. Also one more requirement is that the tasks can be composed of other tasks (one task might depend on another task and call it and wait for it to finish)..
Is there a general design pattern related to something like this that already exists?
Virgil Dobjanschis Google IO REST explains a great pattern for decoupling network operations (REST in his case) from the UI, you can watch the video here http://www.youtube.com/watch?v=xHXn3Kg2IQE it should be a great inspiration to get you started.
Simplest one i can think off, and i'm afraid i'm not a design pattern guru or anything, is the command pattern, certainly a starting point for something a bit more complicated.
http://en.wikipedia.org/wiki/Command_pattern

Categories

Resources