android / android-ktx

A set of Kotlin extensions for Android app development.
https://android.github.io/android-ktx/core-ktx/
7.47k stars 563 forks source link

Feature Suggestion : doBackground / Easier async task #301

Open geniushkg opened 6 years ago

geniushkg commented 6 years ago

Hey team, Thanks for this effort, I appreciate your hard work in making developer's life easier.

New Feature : Do in Background using coroutines doInBg{ .. }

Similar implementation in Anko Anko coroutines

I got the inspiration from #196 which was closed, so this issue will be focused on AsyncTask/Background operation using coroutines.

Please add your valuable suggestion.

illuzor commented 6 years ago

Coroutines is separate library, which must be connected to this library.

Maybe something like this?

geniushkg commented 6 years ago

@illuzor, Kandroid under hood uses threads, anyway thanks for the reference.

SjoerdvGestel commented 6 years ago

@geniushkg or anko-coroutines from JetBrains?

Anko Coroutines is based on the kotlinx.coroutines library and provides:

bg() function that executes your code in a common pool. asReference() function which creates a weak reference wrapper. By default, a coroutine holds references to captured objects until it is finished or canceled. If your asynchronous framework does not support cancellation, the values you use inside the asynchonous block can be leaked. asReference() protects you from this.

https://github.com/Kotlin/anko

Muhannad508 commented 6 years ago

Hey @geniushkg , please tell me what do u think about this implementation . I have tested it, and it works fine

val execute = AsyncTaskKTX<Int, Int, Int>().runInBackground {
            doInBg {
                println("doInBg function in test , Thread : ${Thread.currentThread().name}")
                Assert.assertEquals(4, it.size)
                for (i in 1..5) {
                    Thread.sleep(1000)
                    publishProgress(i)
                }
                it.size
            }

            onUpdate {
                println("onUpdate (${it[0]}) function in test , Thread : ${Thread.currentThread().name}")

            }
        }.execute(3, 4, 5, 6)

where AsyncTaskKTX is extend of AsyncTask .

class AsyncTaskKTX<Params, Progress, Result> : AsyncTask<Params, Progress, Result>()

geniushkg commented 6 years ago

@Muhannad508 this does sounds ok, as @SjoerdvGestel refered anko, I am planning something with coroutines, coroutines is performance wise lighter then creating thread and offloading task to background thread.

Anyway if you have some spare time feel free to send PR, may get accepted by google devs.

Muhannad508 commented 6 years ago

Hey @geniushkg , if you are still working on implementing this feature, then take a look at this article below. hope it helps you avoid all the limitations/problems that already exist in AsyncTask.

http://blog.danlew.net/2014/06/21/the-hidden-pitfalls-of-asynctask/