Execute hard task in Background Thread, return result in Main ThreadHow to check if current thread is not main threadHow to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?Do zombies exist … in .NET?Handover execution to main thread in androidCorrectly starting a Task on background threadHow to continue Firebase Task on the same threadAndroid Xamarin Thread.Sleep on main thread complete blocks all threadsExecutor Service and Main Thread not executing in parallelDoes Async execute block ui thread?How to run repetitive task in Handler Thread?
Was Switzerland really impossible to invade during WW2?
What is this shrub with berries?
How to persuade recruiters to send me the Job Description?
How to specify and fit a hybrid machine learning - linear model
What is "Wayfinder's Guide to Eberron"?
Should my "average" PC be able to discern the potential of encountering a gelatinous cube from subtle clues?
How does turbine efficiency compare with internal combustion engines if all the turbine power is converted to mechanical energy?
How to think about joining a company whose business I do not understand?
What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?
Does Git delete empty folders?
Is there a known non-euclidean geometry where two concentric circles of different radii can intersect? (as in the novel "The Universe Between")
Are there nouns that change meaning based on gender?
Metal that glows when near pieces of itself
Taking out number of subarrays from an array which contains all the distinct elements of that array
Running script line by line automatically yet being asked before each line from second line onwards
Are required indicators necessary for radio buttons?
Overwrite file only if data
Thread-safe, Convenient and Performant Random Number Generator
How to organize ideas to start writing a novel?
How can I support the recycling, but not the new production of aluminum?
Can my boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?
Is it safe to remove the bottom chords of a series of garage roof trusses?
How would one country purchase another?
What's /System/Volumes/Data?
Execute hard task in Background Thread, return result in Main Thread
How to check if current thread is not main threadHow to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?Do zombies exist … in .NET?Handover execution to main thread in androidCorrectly starting a Task on background threadHow to continue Firebase Task on the same threadAndroid Xamarin Thread.Sleep on main thread complete blocks all threadsExecutor Service and Main Thread not executing in parallelDoes Async execute block ui thread?How to run repetitive task in Handler Thread?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I spent some time to find a developer friendly solution (without adding dependencies to the project) of how to perform some hard task in background thread and after the task is completed return result to main thread. I found "AsyncTask" which allows to do that. But to use it you need to write boilerplate code for each task you need to run in Background. I am iOS developer who decided to try Android-related developing. So in Swift you can simply use the next code to make this task:
DispatchQueue.global().async(execute:
//Do some hard task in background
DispatchQueue.main.async(execute:
//Return to main
)
)
This looks pretty simple. But in Kotlin I didn't find such simple solution and decided to create it.
Here is what I made:
I created Generic class
import android.os.AsyncTask
class BaseAsyncTask<M>: AsyncTask<()->M, Int, M>()
var completion: ((M)->Unit)? = null
override fun doInBackground(vararg params: (() -> M)?): M?
for (p in params)
return p?.invoke()
return null
override fun onPostExecute(result: M)
super.onPostExecute(result)
completion?.invoke(result)
And Manager
class AsyncManager
companion object
fun <M>execute(inBackground: ()->M, inMain: (M)->Unit): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.completion = inMain
task.execute(inBackground)
return task
fun <M>execute(inBackground: ()->M): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.execute(inBackground)
return task
Now I use it like this:
AsyncManager.execute(
//Do some hard task in background
,
//Return to main
)
Looks developer friendly.
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED")
AsyncManager.execute(
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
,
Log.e("TASK", "Started task in Main thread with result from Background: " + it)
)
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED - 1")
And the log:
2019-03-27 17:11:00.719 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED
2019-03-27 17:11:00.722 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED - 1
2019-03-27 17:11:00.722 17082-17124/com.test.testapp E/TASK: Started
background task
2019-03-27 17:11:05.737 17082-17124/com.test.testapp E/TASK: Finished
background task with result: The value from background
2019-03-27 17:11:05.738 17082-17082/com.test.testapp E/TASK: Started
task in Main thread with result from Background: The value from
background
So the question is what professional Android developers think about this solution. What problem can I get in case I'll use it. And maybe there is some reason not to use this solution.
android multithreading kotlin android-asynctask
add a comment |
I spent some time to find a developer friendly solution (without adding dependencies to the project) of how to perform some hard task in background thread and after the task is completed return result to main thread. I found "AsyncTask" which allows to do that. But to use it you need to write boilerplate code for each task you need to run in Background. I am iOS developer who decided to try Android-related developing. So in Swift you can simply use the next code to make this task:
DispatchQueue.global().async(execute:
//Do some hard task in background
DispatchQueue.main.async(execute:
//Return to main
)
)
This looks pretty simple. But in Kotlin I didn't find such simple solution and decided to create it.
Here is what I made:
I created Generic class
import android.os.AsyncTask
class BaseAsyncTask<M>: AsyncTask<()->M, Int, M>()
var completion: ((M)->Unit)? = null
override fun doInBackground(vararg params: (() -> M)?): M?
for (p in params)
return p?.invoke()
return null
override fun onPostExecute(result: M)
super.onPostExecute(result)
completion?.invoke(result)
And Manager
class AsyncManager
companion object
fun <M>execute(inBackground: ()->M, inMain: (M)->Unit): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.completion = inMain
task.execute(inBackground)
return task
fun <M>execute(inBackground: ()->M): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.execute(inBackground)
return task
Now I use it like this:
AsyncManager.execute(
//Do some hard task in background
,
//Return to main
)
Looks developer friendly.
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED")
AsyncManager.execute(
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
,
Log.e("TASK", "Started task in Main thread with result from Background: " + it)
)
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED - 1")
And the log:
2019-03-27 17:11:00.719 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED
2019-03-27 17:11:00.722 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED - 1
2019-03-27 17:11:00.722 17082-17124/com.test.testapp E/TASK: Started
background task
2019-03-27 17:11:05.737 17082-17124/com.test.testapp E/TASK: Finished
background task with result: The value from background
2019-03-27 17:11:05.738 17082-17082/com.test.testapp E/TASK: Started
task in Main thread with result from Background: The value from
background
So the question is what professional Android developers think about this solution. What problem can I get in case I'll use it. And maybe there is some reason not to use this solution.
android multithreading kotlin android-asynctask
add a comment |
I spent some time to find a developer friendly solution (without adding dependencies to the project) of how to perform some hard task in background thread and after the task is completed return result to main thread. I found "AsyncTask" which allows to do that. But to use it you need to write boilerplate code for each task you need to run in Background. I am iOS developer who decided to try Android-related developing. So in Swift you can simply use the next code to make this task:
DispatchQueue.global().async(execute:
//Do some hard task in background
DispatchQueue.main.async(execute:
//Return to main
)
)
This looks pretty simple. But in Kotlin I didn't find such simple solution and decided to create it.
Here is what I made:
I created Generic class
import android.os.AsyncTask
class BaseAsyncTask<M>: AsyncTask<()->M, Int, M>()
var completion: ((M)->Unit)? = null
override fun doInBackground(vararg params: (() -> M)?): M?
for (p in params)
return p?.invoke()
return null
override fun onPostExecute(result: M)
super.onPostExecute(result)
completion?.invoke(result)
And Manager
class AsyncManager
companion object
fun <M>execute(inBackground: ()->M, inMain: (M)->Unit): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.completion = inMain
task.execute(inBackground)
return task
fun <M>execute(inBackground: ()->M): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.execute(inBackground)
return task
Now I use it like this:
AsyncManager.execute(
//Do some hard task in background
,
//Return to main
)
Looks developer friendly.
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED")
AsyncManager.execute(
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
,
Log.e("TASK", "Started task in Main thread with result from Background: " + it)
)
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED - 1")
And the log:
2019-03-27 17:11:00.719 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED
2019-03-27 17:11:00.722 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED - 1
2019-03-27 17:11:00.722 17082-17124/com.test.testapp E/TASK: Started
background task
2019-03-27 17:11:05.737 17082-17124/com.test.testapp E/TASK: Finished
background task with result: The value from background
2019-03-27 17:11:05.738 17082-17082/com.test.testapp E/TASK: Started
task in Main thread with result from Background: The value from
background
So the question is what professional Android developers think about this solution. What problem can I get in case I'll use it. And maybe there is some reason not to use this solution.
android multithreading kotlin android-asynctask
I spent some time to find a developer friendly solution (without adding dependencies to the project) of how to perform some hard task in background thread and after the task is completed return result to main thread. I found "AsyncTask" which allows to do that. But to use it you need to write boilerplate code for each task you need to run in Background. I am iOS developer who decided to try Android-related developing. So in Swift you can simply use the next code to make this task:
DispatchQueue.global().async(execute:
//Do some hard task in background
DispatchQueue.main.async(execute:
//Return to main
)
)
This looks pretty simple. But in Kotlin I didn't find such simple solution and decided to create it.
Here is what I made:
I created Generic class
import android.os.AsyncTask
class BaseAsyncTask<M>: AsyncTask<()->M, Int, M>()
var completion: ((M)->Unit)? = null
override fun doInBackground(vararg params: (() -> M)?): M?
for (p in params)
return p?.invoke()
return null
override fun onPostExecute(result: M)
super.onPostExecute(result)
completion?.invoke(result)
And Manager
class AsyncManager
companion object
fun <M>execute(inBackground: ()->M, inMain: (M)->Unit): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.completion = inMain
task.execute(inBackground)
return task
fun <M>execute(inBackground: ()->M): BaseAsyncTask<M>
val task = BaseAsyncTask<M>()
task.execute(inBackground)
return task
Now I use it like this:
AsyncManager.execute(
//Do some hard task in background
,
//Return to main
)
Looks developer friendly.
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED")
AsyncManager.execute(
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
,
Log.e("TASK", "Started task in Main thread with result from Background: " + it)
)
Log.e("MAIN", "MAIN THREAD SHOULD NOT BE BLOCKED - 1")
And the log:
2019-03-27 17:11:00.719 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED
2019-03-27 17:11:00.722 17082-17082/com.test.testapp E/MAIN: MAIN
THREAD SHOULD NOT BE BLOCKED - 1
2019-03-27 17:11:00.722 17082-17124/com.test.testapp E/TASK: Started
background task
2019-03-27 17:11:05.737 17082-17124/com.test.testapp E/TASK: Finished
background task with result: The value from background
2019-03-27 17:11:05.738 17082-17082/com.test.testapp E/TASK: Started
task in Main thread with result from Background: The value from
background
So the question is what professional Android developers think about this solution. What problem can I get in case I'll use it. And maybe there is some reason not to use this solution.
android multithreading kotlin android-asynctask
android multithreading kotlin android-asynctask
edited Mar 27 at 15:48
Dmitry
asked Mar 27 at 15:25
DmitryDmitry
1,88811 silver badges31 bronze badges
1,88811 silver badges31 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
If you're using Kotlin, the correct way to do this is via Coroutines, which would allow you to write code such as:
// Launch a coroutine that by default goes to the main thread
GlobalScope.launch(Dispatchers.Main)
// Switch to a background (IO) thread
val retval = withContext(Dispatchers.IO)
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
// Now you're back the main thread
Log.e("TASK", "Started task in Main thread with result from Background: " + retval)
Note that Kotlin coroutines operate under structured concurrency, so you'd generally want to avoid using GlobalScope
and instead scope your coroutine to be tied to your Activity / Fragment lifecycle. This generally needs to be done yourself right now.
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380856%2fexecute-hard-task-in-background-thread-return-result-in-main-thread%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you're using Kotlin, the correct way to do this is via Coroutines, which would allow you to write code such as:
// Launch a coroutine that by default goes to the main thread
GlobalScope.launch(Dispatchers.Main)
// Switch to a background (IO) thread
val retval = withContext(Dispatchers.IO)
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
// Now you're back the main thread
Log.e("TASK", "Started task in Main thread with result from Background: " + retval)
Note that Kotlin coroutines operate under structured concurrency, so you'd generally want to avoid using GlobalScope
and instead scope your coroutine to be tied to your Activity / Fragment lifecycle. This generally needs to be done yourself right now.
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
add a comment |
If you're using Kotlin, the correct way to do this is via Coroutines, which would allow you to write code such as:
// Launch a coroutine that by default goes to the main thread
GlobalScope.launch(Dispatchers.Main)
// Switch to a background (IO) thread
val retval = withContext(Dispatchers.IO)
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
// Now you're back the main thread
Log.e("TASK", "Started task in Main thread with result from Background: " + retval)
Note that Kotlin coroutines operate under structured concurrency, so you'd generally want to avoid using GlobalScope
and instead scope your coroutine to be tied to your Activity / Fragment lifecycle. This generally needs to be done yourself right now.
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
add a comment |
If you're using Kotlin, the correct way to do this is via Coroutines, which would allow you to write code such as:
// Launch a coroutine that by default goes to the main thread
GlobalScope.launch(Dispatchers.Main)
// Switch to a background (IO) thread
val retval = withContext(Dispatchers.IO)
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
// Now you're back the main thread
Log.e("TASK", "Started task in Main thread with result from Background: " + retval)
Note that Kotlin coroutines operate under structured concurrency, so you'd generally want to avoid using GlobalScope
and instead scope your coroutine to be tied to your Activity / Fragment lifecycle. This generally needs to be done yourself right now.
If you're using Kotlin, the correct way to do this is via Coroutines, which would allow you to write code such as:
// Launch a coroutine that by default goes to the main thread
GlobalScope.launch(Dispatchers.Main)
// Switch to a background (IO) thread
val retval = withContext(Dispatchers.IO)
Log.e("TASK", "Started background task")
val retval = "The value from background"
Thread.sleep(5000)
Log.e("TASK", "Finished background task with result: " + retval)
retval
// Now you're back the main thread
Log.e("TASK", "Started task in Main thread with result from Background: " + retval)
Note that Kotlin coroutines operate under structured concurrency, so you'd generally want to avoid using GlobalScope
and instead scope your coroutine to be tied to your Activity / Fragment lifecycle. This generally needs to be done yourself right now.
answered Mar 27 at 15:34
ianhanniballakeianhanniballake
114k15 gold badges234 silver badges255 bronze badges
114k15 gold badges234 silver badges255 bronze badges
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
add a comment |
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
Thanks for the answer. I was looking for the solution without adding dependencies to the project.
– Dmitry
Mar 27 at 15:46
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
@Dmitry - I think you need to get over that mental model. Writing a much worse version of something that already exists 100x better and better tested is never a sustainable approach.
– ianhanniballake
Mar 27 at 15:50
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
Thank you. I'll think about this.
– Dmitry
Mar 27 at 16:00
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380856%2fexecute-hard-task-in-background-thread-return-result-in-main-thread%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown