How to wait for AsyncTask to finish? - android

I have to call server through the API call. My API call is AsyncTask with doInBackground() containing server GET. onPostExecute() will get result from server and it will return JSON back to my activity.
Problem is, that I'm using this api call inside the method with return parameter.
Some pseudocode here:
private fun getDataFromServer(apiParam: Int): ArrayList<Objects> {
var extractedObjects: ArrayList<Objects> = ArrayList()
api.getDataByParameter(apiParam, object: APICallback{
override fun onError(errorJSON: JSONObject) {
errorLog: errorJSON
}
override fun onSuccess(resultJSON: JSONObject) {
extractedObjects = getObjectsFromJSON(resultJSON)
}
})
return extractedObjects
}
Adding my API Call from API class (custom class):
fun getDataByParameter(apiParam: Int, callback: APICallback){
class GetDataAsync(private val dataCallback: APICallback): AsyncTask<Void, Void, JSONObject>() {
override fun doInBackground(vararg p0: Void?): JSONObject {
val server = Server.getInstance(context!!)
return server.doGet(apiURL + apiParam.toString() + "/")
}
override fun onPostExecute(result: JSONObject) {
super.onPostExecute(result)
if (result!!.has("data_objects")){
dataCallback.onSuccess(result)
} else {
dataCallback.onError(result)
}
}
}
GetDataAsync(callback).execute()
}
interface APICallback{
fun onError(errorJSON:JSONObject)
fun onSuccess(resultJSON:JSONObject)
}
As you can see, I have to extract objects from JSONObject and convert it to ArrayList<Objects> (sometimes do other stuff like filtering). So what will happen in my program. As I call getDataFromServer it will call AsyncTask to my server and after that it will return empty ArrayList. Until result is available in onSuccess, method is already over.
So I need to wait for onSuccess and also I have to wait for getObjectsFromJSON() to be finished. After that I can return my full list of objects.
Is there any way how to achieve this? I cant do synchronous task, because it will fire NetworkOnMainThreadException. I have to do it in second thread, but also my main thread has to wait for results.

I have to do it in second thread, but also my main thread has to wait for results.
Clearly, these are two contradictory requirements. The point of the NetworkOnMainThreadException isn't the "network" part, but the fact that it's a blocking network call. You aren't allowed to perform any kind of blocking calls on the UI thread, be it network or anything else.
What you must do is arrange for your splash screen to be removed within the onPostExecute call instead of the UI callback method where you show it.
I would highly recommend upgrading your project to Kotlin Coroutines because with them you can avoid all the messy callbacks and write sequential-looking code which nevertheless satisfies the rules of the UI thread. As an outline, this is how your code would look:
class StartActivity : AppCompatActivity, CoroutineContext {
lateinit var masterJob: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + masterJob
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
masterJob = Job()
this.launch {
showSplash()
val result = makeNetworkCall()
updateState(result)
hideSplash()
}
}
suspend fun StartActivity.makeNetworkCall() = withContext(Dispatchers.IO) {
Server.getInstance(this).doGet(apiURL + apiParam.toString() + "/")
}
override fun onDestroy() {
super.onDestroy()
job.cancel() // Automatically cancels all child jobs
}
}

Do the network call inside doInBackground().
get the result from onPostExecute() in the Async task.

Related

RxJava BehaviorSubject subcribeoN

Below Code
why onnext called only once? When I remove subscribeOn it was called for every number.
when I subscribeOn io thread just once called (for 8658)
can someone explain it to me?
val subject = BehaviorSubject.create<Int>()
subject.onNext(2121)
subject.distinctUntilChanged().doOnNext {
Log.d("AHMET VEFA SARUHAN", it.toString())
}.subscribeOn(Schedulers.io()).subscribe(object : Observer<Int> {
override fun onSubscribe(d: Disposable?) {
}
override fun onNext(t: Int?) {
}
override fun onError(e: Throwable?) {
}
override fun onComplete() {
}
})
subject.onNext(5436)
subject.onNext(8658)
By using subscribeOn, the chain to observe the BehaviorSubject is established concurrently with the thread calling the onNexts. It takes time for a subscribeOn to take effect thus the main thread simply runs ahead and overwrites the subject's current value to the latest in the meantime.
There is no practical reason to use subscribeOn on a Subject in general.

How to wait until a bunch of calls ends to make another call

I'm using RxJava and I know about concat, and I guess it does fit to me, because I want to finish first all of first call and then do the second one but I don't know how to implement it.
I have this from now :
private fun assignAllAnswersToQuestion(questionId: Long) {
answerListCreated.forEach { assignAnswerToQuestion(questionId, it.id) }
}
private fun assignAnswerToQuestion(questionId: Long, answerId: Long) {
disposable = questionService.addAnswerToQuestion(questionId,answerId,MyUtils.getAccessTokenFromLocalStorage(context = this))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
result -> //Do nothing it should call the next one
},
{ error -> toast(error.message.toString())}
)
}
But then, once this is finished all of this forEach I'd like to do something like this :
private fun assignAllAnswersToQuestion(questionId: Long) {
answerListCreated.forEach { assignAnswerToQuestion(questionId, it.id)
anotherCallHere(questionId) //Do it when the first forEach is finished!!
}
Any idea?
Also, is a way to do it with coroutines this?
I think you have to .map your list (answerListCreated) to a list of Flowables, and then use Flowable.zip on this list.
zip is used to combine the results of the Flowables into a single result. Since you don't need these results we ignore them.
After zip you are sure that all previous Flowables ended, and you can .flatMap to execute your next call (assuming anotherCallHere returns a Flowable.
In the end, it will be something like:
val flowableList = answerListCreated.map { assignAnswerToQuestion(questionId, it.id) }
disposable = Flowable.zip(flowableList) { /* Ignoring results */ }
.flatMap { anotherCallHere(questionId) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
// ...
}
It should be noted that if any of the calls fails, the whole chain will fail (onError will be called).
I'm new to coroutines but I think I can answer for them:
You can use coroutines runBlocking {} for this.
private fun assignAllAnswersToQuestion(questionId: Long) = launch {
runBlocking {
answerListCreated.forEach { assignAnswerToQuestion(questionId, it.id) }
}
anotherCallHere(questionId)
}
private fun assignAnswerToQuestion(questionId: Long, answerId: Long) = launch (Dispatchers.IO) {
questionService.addAnswerToQuestion(
questionId,
answerId,
MyUtils.getAccessTokenFromLocalStorage(context = this)
)
}
launch {} returns a Job object which becomes a child job of the parent coroutine. runBlocking {} will block until all its child jobs have finished, (an alternative is to use launch {}.join() which will have the same affect).
Note that I have made both functions wrap their code in a launch {} block.
To be able to call launch {} like this, you will likely want to make your class implement CoroutineScope
class MyActivityOrFragment: Activity(), CoroutineScope {
lateinit var job = SupervisorJob()
private val exceptionHandler =
CoroutineExceptionHandler { _, error ->
toast(error.message.toString()
}
override val coroutineContext = Dispatchers.Main + job + exceptionHandler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
...
}

Wait For Data Inside a Listener in a Coroutine

I have a coroutine I'd like to fire up at android startup during the splash page. I'd like to wait for the data to come back before I start the next activity. What is the best way to do this? Currently our android is using experimental coroutines 0.26.0...can't change this just yet.
UPDATED: We are now using the latest coroutines and no longer experimental
onResume() {
loadData()
}
fun loadData() = GlobalScope.launch {
val job = GlobalScope.async {
startLibraryCall()
}
// TODO await on success
job.await()
startActivity(startnewIntent)
}
fun startLibraryCall() {
val thirdPartyLib() = ThirdPartyLibrary()
thirdPartyLib.setOnDataListener() {
///psuedocode for success/ fail listeners
onSuccess -> ///TODO return data
onFail -> /// TODO return other data
}
}
The first point is that I would change your loadData function into a suspending function instead of using launch. It's better to have the option to define at call site how you want to proceed with the execution. For example when implementing a test you may want to call your coroutine inside a runBlocking. You should also implement structured concurrency properly instead of relying on GlobalScope.
On the other side of the problem I would implement an extension function on the ThirdPartyLibrary that turns its async calls into a suspending function. This way you will ensure that the calling coroutine actually waits for the Library call to have some value in it.
Since we made loadData a suspending function we can now ensure that it will only start the new activity when the ThirdPartyLibrary call finishes.
import kotlinx.coroutines.*
import kotlin.coroutines.*
class InitialActivity : AppCompatActivity(), CoroutineScope {
private lateinit var masterJob: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + masterJob
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
masterJob = Job()
}
override fun onDestroy() {
super.onDestroy()
masterJob.cancel()
}
override fun onResume() {
this.launch {
val data = ThirdPartyLibrary().suspendLoadData()
// TODO: act on data!
startActivity(startNewIntent)
}
}
}
suspend fun ThirdPartyLibrary.suspendLoadData(): Data = suspendCoroutine { cont ->
setOnDataListener(
onSuccess = { cont.resume(it) },
onFail = { cont.resumeWithException(it) }
)
startLoadingData()
}
You can use LiveData
liveData.value = job.await()
And then add in onCreate() for example
liveData.observe(currentActivity, observer)
In observer just wait until value not null and then start your new activity
Observer { result ->
result?.let {
startActivity(newActivityIntent)
}
}

How to properly wait for HandlerThread to start before doing something?

In My project sometimes the created thread does not start as fast as it should be, This happens on a minimal occasions but mostly will happen on slow/older phones.
I my Thread like..
class DBThread(threadName: String) : HandlerThread(threadName) {
private var mWorkerHandler: Handler? = null
override fun onLooperPrepared() {
super.onLooperPrepared()
mWorkerHandler = Handler(looper)
}
fun createTask(task: Runnable) {
mWorkerHandler?.post(task)
}
}
and when i use it and call on activity..
//this will handle db queries on background and not on main ui thread
var mDbThread: DBThread = DBThread("dbThread")
//use this to interact to main ui thread from different thread
val mUiHandler = Handler()
var mDb: LocalDatabase? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mDbThread.start()
mDb = LocalDatabase.getInstance(this)
fetchAndSetList()
}
override fun onDestroy() {
super.onDestroy()
LocalDatabase.destroyInstance()
mDbThread.quitSafely()
}
private fun fetchAndSetList(){
mDbThread.createTask(Runnable {
val list = getList()
mUiHandler.post {
// this sometimes does not trigger
setList(list)
}
})
}
the function setList does not trigger on sometimes.
And so i did something like this.
fun createTask(task: Runnable) {
if(mWorkerHandler == null ){
createTask(task)
return
}
mWorkerHandler?.post(task)
}
the modified action seems to work however I'm not quite sure if this is a SAFE way to do this. Thank you in advance.
I think the reason why mWorkerhandler is null is because Thread.start will create the new VMThread and start the looper in the VMThread. The whole flow is asynchronous so when onLooperPrepared actually is called, it's too late because "fetchAndSetList" is already trying to use mWorkerHandler
The solution is create the handler outside of the HandlerThread:
Handler workerHandler;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mDbThread.start()
workerHandler = new Handler(mDbThread.getLooper());
mDb = LocalDatabase.getInstance(this)
fetchAndSetList()
}
private fun fetchAndSetList(){
workerHandler.post(Runnable {
val list = getList()
mUiHandler.post {
// this sometimes does not trigger
setList(list)
}
})
}

How to replace AsyncTask and AsyncTaskLoader with their Rx equivalents?

Background
Some articles claim that Rx can replace AsyncTask and AsyncTaskLoader.
Seeing that Rx usually makes code shorter, I tried to dive into various samples and ideas of how it works.
The problem
All of the samples and articles I've found, including Github repos, don't seem to really replace AsyncTask and AsyncTaskLoader well:
Can't find how to cancel a task or multiple ones (including interrupting a thread). This is especially important for AsyncTask, which is usually used for RecyclerView and ListView. This can also be done on AsyncTaskLoader, but requires a bit more work than just call "cancel". For AsyncTask, it also provides publishing of a progress, and that's another thing I can't find an example of in Rx.
Can't find how to avoid unsubscribing manually while avoiding memory leaks, which quite ruins the whole point of using Rx, as it's supposed to be shorter. In some samples, there are even more callbacks than normal code has.
What I've tried
Here are some links I've read about Rx:
https://stablekernel.com/replace-asynctask-and-asynctaskloader-with-rx-observable-rxjava-android-patterns/ - this actually provides a cool way to handle AsyncTaskLoader, as it caches the result. However, the samples don't work at all (including building them), as they are very old.
https://code.tutsplus.com/tutorials/getting-started-with-rxjava-20-for-android--cms-28345 , https://code.tutsplus.com/tutorials/reactive-programming-operators-in-rxjava-20--cms-28396 , https://code.tutsplus.com/tutorials/rxjava-for-android-apps-introducing-rxbinding-and-rxlifecycle--cms-28565 - all those talk mostly about RxJava, and not about replacement of AsyncTask or AsyncTaskLoader.
https://github.com/L4Digital/RxLoader - requires unsubscribing, even though it doesn't say it needs it.
The question
How can I use Rx as replacement for AsyncTask and AsyncTaskLoader?
For example, how would I replace this tiny AsyncTaskLoader sample code with Rx equivalent:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportLoaderManager.initLoader(1, Bundle.EMPTY, object : LoaderCallbacks<Int> {
override fun onCreateLoader(id: Int, args: Bundle): Loader<Int> {
Log.d("AppLog", "onCreateLoader")
return MyLoader(this#MainActivity)
}
override fun onLoadFinished(loader: Loader<Int>, data: Int?) {
Log.d("AppLog", "done:" + data!!)
}
override fun onLoaderReset(loader: Loader<Int>) {}
})
}
private class MyLoader(context: Context) : AsyncTaskLoader<Int>(context) {
override fun onStartLoading() {
super.onStartLoading()
forceLoad()
}
override fun loadInBackground(): Int {
Log.d("AppLog", "loadInBackground")
try {
Thread.sleep(10000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
return 123
}
}
}
For AsyncTask, usually we set it per ViewHolder, as a field there, and we cancel it upon onBindViewHolder, and when activity/fragment gets destroyed (go over all those that still pending or running).
Something like this (sample made as short as possible, of course it should be changed depending on needs) :
class AsyncTaskActivity : AppCompatActivity() {
internal val mTasks = HashSet<AsyncTask<Void, Int, Void>>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_async_task)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = object : Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(this#AsyncTaskActivity).inflate(android.R.layout.simple_list_item_1, parent, false))
}
#SuppressLint("StaticFieldLeak")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.tv.text = "loading..."
if (holder.task != null) {
holder.task!!.cancel(true)
mTasks.remove(holder.task!!)
}
holder.task = object : AsyncTask<Void, Int, Void>() {
override fun doInBackground(vararg voids: Void): Void? {
for (i in 0..100)
try {
Thread.sleep(5)
publishProgress(i)
} catch (e: InterruptedException) {
e.printStackTrace()
}
return null
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
holder.tv.text = "progress:" + values[0]
}
override fun onPostExecute(aVoid: Void?) {
super.onPostExecute(aVoid)
mTasks.remove(holder.task)
holder.tv.text = "done:" + position
holder.task = null
}
}.execute()
}
override fun getItemCount(): Int {
return 1000
}
}
}
override fun onDestroy() {
super.onDestroy()
for (task in mTasks)
task.cancel(true)
}
private class MyViewHolder(itemView: View) : ViewHolder(itemView) {
internal var tv: TextView
internal var task: AsyncTask<Void, Int, Void>? = null
init {
tv = itemView.findViewById(android.R.id.text1)
}
}
}
Let me tell you in advance that my experience in RxJava isn't as some would call it advance. I just know enough to replace AsyncTask using RxJava + RxAndroid. For example, let's convert your AsyncTask code to RxJava2 equivalent using Observable, which is arguably the most popular stream type.
Observable
.create <Int> { emitter ->
try {
for (i in 0..100) {
Thread.sleep(5)
emitter.onNext(i)
}
} catch (e: InterruptedException) {
emitter.onError(e)
}
emitter.onComplete()
‎}
‎.subscribeOn(Schedulers.io())
‎.observeOn(AndroidSchedulers.mainThread())
‎.subscribe({ i ->
‎ holder.tv.text = "progress:" + i
}, { e ->
‎ e.printStackTrace()
‎}, {
‎ holder.tv.text = "done:" + position
‎})
Now let's go through the code line-by-line:
create lets you customize emitter behavior. Note that this isn't the only method to create the streams, there are also just, fromArray, fromList, defer, etc. We can discuss more of that if you are still interested.
subscribeOn(Schedulers.io()) tells RxJava that #1 will be executed in I/O thread. If this is a background operation, Schedulers.newThread() also works (at least to my knowledge it does).
observeOn(AndroidSchedulers.mainThread()) tells RxJava that #4 will be executed in Android's main thread. This is also where RxAndroid fills the gap since RxJava doesn't have any reference of Android.
subscribe()
onNext(i : Int) - equivalent to publishProgress(). In newer RxJava, emitted value cannot be null.
onError(e : Throwable) - error handling that is long glorified by RxJava's programmers. In newer RxJava, onError() must be provided, doesn't matter if it's empty.
onComplete() - equivalent to onPostExecute().
Again, there might be a lot of misinformation with my answer. I expect someone with better understanding to correct it or provide better answer that this one.
It seems there is no way to implement AsyncTask functionality with RxJava in shorter or more simple form. With RxJava you simplify task chaining, so if you have only one task AsyncTask can be better solution, but when you have several consecutive tasks to do - RxJava's interface is more convenient. So instead of, for example, program onCancelled for each task you should rather implement some common logic.

Categories

Resources