Optimal solution for utilizing the same AsyncTask repeatedly? - android

I know that an AsyncTask can be run only once. I know a way around that, but I need a variable from the AsyncTask that uses complicated(?) processes. This is my code for calling the AsyncTask
val thr=NewTask()
thr.delegate = this
button.setOnClickListener {
thr.execute()
}
NewTask.doOnBackground() is just a normal method sending the request to the URL. onPostExecute() is a bit different:
public override fun onPostExecute(result: String?) {
//super.onPostExecute(result)
delegate!!.processFinish(result!!)
}
with delegate being a variable of AsyncResponse? which is an interface containing processFinish abstract method taking a string and returning nothing.
My question is, how can I run the AsyncTask repeatedly while still getting the response? Thanks in advance.

Finally, I settled on using coroutines with this. Coroutines are easy to use, much easier than AsyncTask. I don't know why I was scared of them. Here is the code I used:
class CoRoutine{
suspend fun httpGet(url: String = "https://boogle.org"): String {
val arr = ArrayList<String>()
withContext(Dispatchers.IO) {
val url = URL(url)
with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET
//arr.add(responseCode)
inputStream.bufferedReader().use {
it.lines().forEach { line ->
//println(line)
arr.add(line as String)
}
}
}
}
return arr.get(0)
}
}

Related

How to call multiple api concurrently and read headers using Retrofit, Coroutines with Async/Await method in Kotlin Android

My aim to call five apis and to get headers from those api response.
I have added my code below
Api service class
#GET("users")
suspend fun getUserList(): Call<List<FriendListModel>>
Repo class
suspend fun getList(): Response<List<FriendListModel>> {
return apiService.getUserList().execute()
}
ViewModel class
fun getFriends() {
viewModelScope.launch(Dispatchers.IO) {
val data =
async {
try {
val data = friendListRepo.getList()
val header = data.headers().get("id")
/*
* need to add header logic
*/
Resource.success(data)
} catch (throwable: Throwable) {
when (throwable) {
is HttpException -> {
Resource.error(false, throwable.response()?.message()?:"")
}
else -> {
Resource.error(false, "")
}
}
}
}
val res = data.await()
mutableFriendsList.postValue(res)
}
}
My question is, am I doing it in right way because I am getting a warning in repo class saying that "Inappropriate blocking method call" since I am calling execute() method though I am calling it in suspend function.
[I referred] Kotlin coroutines await for 2 or more different concurrent requests.
Is there any other approach to achieve this?
You should not combine suspend with Call. Call is for asynchronous work. suspend does asynchronous work synchronously by suspending. It can't be both at once. execute does a blocking synchronous fetch of the data, which shouldn't be done in a coroutine.
So, your functions should look like:
#GET("users")
suspend fun getUserList(): List<FriendListModel>
suspend fun getList(): List<FriendListModel> {
return apiService.getUserList()
}
Then when you use it in a coroutine, you don't need async because you're just calling a synchronous suspend function. You also don't need to fool with Dispatchers.IO since you're only using a suspend function (not doing blocking work). I also simplified your catch block in this example, but that's not related to the solution (I just couldn't help myself).
fun getFriends() {
viewModelScope.launch {
mutableFriendsList.value = try {
val data = friendListRepo.getList()
val header = data.headers().get("id")
/*
* need to add header logic
*/
Resource.success(data)
} catch (throwable: Throwable) {
Resource.error(false, (throwable as? HttpException)?.response()?.message.orEmpty())
}
}
}
Side note, even when you are calling blocking code, you should never need to use async immediately followed by an await() call on it. That is just a convoluted alternative to withContext.

How to wait until if statement is done? Kotlin [duplicate]

(Disclaimer: There are a ton of questions which arise from people asking about data being null/incorrect when using asynchronous operations through requests such as facebook,firebase, etc. My intention for this question was to provide a simple answer for that problem to everyone starting out with asynchronous operations in android)
I'm trying to get data from one of my operations, when I debug it using breakpoints or logs, the values are there, but when I run it they are always null, how can I solve this ?
Firebase
firebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
//I want to return these values I receive here...
});
//...and use the returned value here.
Facebook
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"some path",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
//I want to return these values I receive here...
}
});
request.executeAsync();
//...and use the returned value here.
Kotlin coroutine
var result: SomeResultType? = null
someScope.launch {
result = someSuspendFunctionToRetrieveSomething()
//I want to return the value I received here...
}
Log.d("result", result.toString()) //...but it is still null here.
Etc.
What is a Synchronous/Asynchronous operation ?
Well, Synchronous waits until the task has completed. Your code executes "top-down" in this situation.
Asynchronous completes a task in the background and can notify you when it is complete.
If you want to return the values from an async operation through a method/function, you can define your own callbacks in your method/function to use these values as they are returned from these operations.
Here's how for Java
Start off by defining an interface :
interface Callback {
void myResponseCallback(YourReturnType result);//whatever your return type is: string, integer, etc.
}
next, change your method signature to be like this :
public void foo(final Callback callback) { // make your method, which was previously returning something, return void, and add in the new callback interface.
next up, wherever you previously wanted to use those values, add this line :
callback.myResponseCallback(yourResponseObject);
as an example :
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
// create your object you want to return here
String bar = document.get("something").toString();
callback.myResponseCallback(bar);
})
now, where you were previously calling your method called foo:
foo(new Callback() {
#Override
public void myResponseCallback(YourReturnType result) {
//here, this result parameter that comes through is your api call result to use, so use this result right here to do any operation you previously wanted to do.
}
});
}
How do you do this for Kotlin ?
(as a basic example where you only care for a single result)
start off by changing your method signature to something like this:
fun foo(callback:(YourReturnType) -> Unit) {
.....
then, inside your asynchronous operation's result :
firestore.collection("something")
.document("document").get()
.addOnSuccessListener {
val bar = it.get("something").toString()
callback(bar)
}
then, where you would have previously called your method called foo, you now do this :
foo() { result->
// here, this result parameter that comes through is
// whatever you passed to the callback in the code aboce,
// so use this result right here to do any operation
// you previously wanted to do.
}
// Be aware that code outside the callback here will run
// BEFORE the code above, and cannot rely on any data that may
// be set inside the callback.
if your foo method previously took in parameters :
fun foo(value:SomeType, callback:(YourType) -> Unit)
you simply change it to :
foo(yourValueHere) { result ->
// here, this result parameter that comes through is
// whatever you passed to the callback in the code aboce,
// so use this result right here to do any operation
// you previously wanted to do.
}
these solutions show how you can create a method/function to return values from async operations you've performed through the use of callbacks.
However, it is important to understand that, should you not be interested in creating a method/function for these:
#Override
public void onSuccess(SomeApiObjectType someApiResult) {
// here, this `onSuccess` callback provided by the api
// already has the data you're looking for (in this example,
// that data would be `someApiResult`).
// you can simply add all your relevant code which would
// be using this result inside this block here, this will
// include any manipulation of data, populating adapters, etc.
// this is the only place where you will have access to the
// data returned by the api call, assuming your api follows
// this pattern
})
There's a particular pattern of this nature I've seen repeatedly, and I think an explanation of what's happening would help. The pattern is a function/method that calls an API, assigning the result to a variable in the callback, and returns that variable.
The following function/method always returns null, even if the result from the API is not null.
Kotlin
fun foo(): String? {
var myReturnValue: String? = null
someApi.addOnSuccessListener { result ->
myReturnValue = result.value
}.execute()
return myReturnValue
}
Kotlin coroutine
fun foo(): String? {
var myReturnValue: String? = null
lifecycleScope.launch {
myReturnValue = someApiSuspendFunction()
}
return myReturnValue
}
Java 8
private String fooValue = null;
private String foo() {
someApi.addOnSuccessListener(result -> fooValue = result.getValue())
.execute();
return fooValue;
}
Java 7
private String fooValue = null;
private String foo() {
someApi.addOnSuccessListener(new OnSuccessListener<String>() {
public void onSuccess(Result<String> result) {
fooValue = result.getValue();
}
}).execute();
return fooValue;
}
The reason is that when you pass a callback or listener to an API function, that callback code will only be run some time in the future, when the API is done with its work. By passing the callback to the API function, you are queuing up work, but the current function (foo() in this case) returns immediately before that work begins and before that callback code is run.
Or in the case of the coroutine example above, the launched coroutine is very unlikely to complete before the function that started it.
Your function that calls the API cannot return the result that is returned in the callback (unless it's a Kotlin coroutine suspend function). The solution, explained in the other answer, is to make your own function take a callback parameter and not return anything.
Alternatively, if you're working with coroutines, you can make your function suspend instead of launching a separate coroutine. When you have suspend functions, somewhere in your code you must launch a coroutine and handle the results within the coroutine. Typically, you would launch a coroutine in a lifecycle function like onCreate(), or in a UI callback like in an OnClickListener.
Other answer explains how to consume APIs based on callbacks by exposing a similar callbacks-based API in the outer function. However, recently Kotlin coroutines become more and more popular, especially on Android and while using them, callbacks are generally discouraged for such purposes. Kotlin approach is to use suspend functions instead. Therefore, if our application uses coroutines already, I suggest not propagating callbacks APIs from 3rd party libraries to the rest of our code, but converting them to suspend functions.
Converting callbacks to suspend
Let's assume we have this callback API:
interface Service {
fun getData(callback: Callback<String>)
}
interface Callback<in T> {
fun onSuccess(value: T)
fun onFailure(throwable: Throwable)
}
We can convert it to suspend function using suspendCoroutine():
private val service: Service
suspend fun getData(): String {
return suspendCoroutine { cont ->
service.getData(object : Callback<String> {
override fun onSuccess(value: String) {
cont.resume(value)
}
override fun onFailure(throwable: Throwable) {
cont.resumeWithException(throwable)
}
})
}
}
This way getData() can return the data directly and synchronously, so other suspend functions can use it very easily:
suspend fun otherFunction() {
val data = getData()
println(data)
}
Note that we don't have to use withContext(Dispatchers.IO) { ... } here. We can even invoke getData() from the main thread as long as we are inside the coroutine context (e.g. inside Dispatchers.Main) - main thread won't be blocked.
Cancellations
If the callback service supports cancelling of background tasks then it is best to cancel when the calling coroutine is itself cancelled. Let's add a cancelling feature to our callback API:
interface Service {
fun getData(callback: Callback<String>): Task
}
interface Task {
fun cancel();
}
Now, Service.getData() returns Task that we can use to cancel the operation. We can consume it almost the same as previously, but with small changes:
suspend fun getData(): String {
return suspendCancellableCoroutine { cont ->
val task = service.getData(object : Callback<String> {
...
})
cont.invokeOnCancellation {
task.cancel()
}
}
}
We only need to switch from suspendCoroutine() to suspendCancellableCoroutine() and add invokeOnCancellation() block.
Example using Retrofit
interface GitHubService {
#GET("users/{user}/repos")
fun listRepos(#Path("user") user: String): Call<List<Repo>>
}
suspend fun listRepos(user: String): List<Repo> {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build()
val service = retrofit.create<GitHubService>()
return suspendCancellableCoroutine { cont ->
val call = service.listRepos(user)
call.enqueue(object : Callback<List<Repo>> {
override fun onResponse(call: Call<List<Repo>>, response: Response<List<Repo>>) {
if (response.isSuccessful) {
cont.resume(response.body()!!)
} else {
// just an example
cont.resumeWithException(Exception("Received error response: ${response.message()}"))
}
}
override fun onFailure(call: Call<List<Repo>>, t: Throwable) {
cont.resumeWithException(t)
}
})
cont.invokeOnCancellation {
call.cancel()
}
}
}
Native support
Before we start converting callbacks to suspend functions, it is worth checking whether the library that we use does support suspend functions already: natively or with some extension. Many popular libraries like Retrofit or Firebase support coroutines and suspend functions. Usually, they either provide/handle suspend functions directly or they provide suspendable waiting on top of their asynchronous task/call/etc. object. Such waiting is very often named await().
For example, Retrofit supports suspend functions directly since 2.6.0:
interface GitHubService {
#GET("users/{user}/repos")
suspend fun listRepos(#Path("user") user: String): List<Repo>
}
Note that we not only added suspend, but also we no longer return Call, but the result directly. Now, we can use it without all this enqueue() boilerplate:
val repos = service.listRepos(user)
TL;DR The code you pass to these APIs (e.g. in the onSuccessListener) is a callback, and it runs asynchronously (not in the order it is written in your file). It runs at some point later in the future to "call back" into your code. Without using a coroutine to suspend the program, you cannot "return" data retrieved in a callback from a function.
What is a callback?
A callback is a piece of code you pass to some third party library that it will run later when some event happens (e.g. when it gets data from a server). It is important to remember that the callback is not run in the order you wrote it - it may be run much later in the future, could run multiple times, or may never run at all. The example callback below will run Point A, start the server fetching process, run Point C, exit the function, then some time in the distant future may run Point B when the data is retrieved. The printout at Point C will always be empty.
fun getResult() {
// Point A
var r = ""
doc.get().addOnSuccessListener { result ->
// The code inside the {} here is the "callback"
// Point B - handle result
r = result // don't do this!
}
// Point C - r="" still here, point B hasn't run yet
println(r)
}
How do I get the data from the callback then?
Make your own interface/callback
Making your own custom interface/callback can sometimes make things cleaner looking but it doesn't really help with the core question of how to use the data outside the callback - it just moves the aysnc call to another location. It can help if the primary API call is somewhere else (e.g. in another class).
// you made your own callback to use in the
// async API
fun getResultImpl(callback: (String)->Unit) {
doc.get().addOnSuccessListener { result ->
callback(result)
}
}
// but if you use it like this, you still have
// the EXACT same problem as before - the printout
// will always be empty
fun getResult() {
var r = ""
getResultImpl { result ->
// this part is STILL an async callback,
// and runs later in the future
r = result
}
println(r) // always empty here
}
// you still have to do things INSIDE the callback,
// you could move getResultImpl to another class now,
// but still have the same potential pitfalls as before
fun getResult() {
getResultImpl { result ->
println(result)
}
}
Some examples of how to properly use a custom callback: example 1, example 2, example 3
Make the callback a suspend function
Another option is to turn the async method into a suspend function using coroutines so it can wait for the callback to complete. This lets you write linear-looking functions again.
suspend fun getResult() {
val result = suspendCoroutine { cont ->
doc.get().addOnSuccessListener { result ->
cont.resume(result)
}
}
// the first line will suspend the coroutine and wait
// until the async method returns a result. If the
// callback could be called multiple times this may not
// be the best pattern to use
println(result)
}
Re-arrange your program into smaller functions
Instead of writing monolithic linear functions, break the work up into several functions and call them from within the callbacks. You should not try to modify local variables within the callback and return or use them after the callback (e.g. Point C). You have to move away from the idea of returning data from a function when it comes from an async API - without a coroutine this generally isn't possible.
For example, you could handle the async data in a separate method (a "processing method") and do as little as possible in the callback itself other than call the processing method with the received result. This helps avoid a lot of the common errors with async APIs where you attempt to modify local variables declared outside the callback scope or try to return things modified from within the callback. When you call getResult it starts the process of getting the data. When that process is complete (some time in the future) the callback calls showResult to show it.
fun getResult() {
doc.get().addOnSuccessListener { result ->
showResult(result)
}
// don't try to show or return the result here!
}
fun showResult(result: String) {
println(result)
}
Example
As a concrete example here is a minimal ViewModel showing how one could include an async API into a program flow to fetch data, process it, and display it in an Activity or Fragment. This is written in Kotlin but is equally applicable to Java.
class MainViewModel : ViewModel() {
private val textLiveData = MutableLiveData<String>()
val text: LiveData<String>
get() = textLiveData
fun fetchData() {
// Use a coroutine here to make a dummy async call,
// this is where you could call Firestore or other API
// Note that this method does not _return_ the requested data!
viewModelScope.launch {
delay(3000)
// pretend this is a slow network call, this part
// won't run until 3000 ms later
val t = Calendar.getInstance().time
processData(t.toString())
}
// anything out here will run immediately, it will not
// wait for the "slow" code above to run first
}
private fun processData(d: String) {
// Once you get the data you may want to modify it before displaying it.
val p = "The time is $d"
textLiveData.postValue(p)
}
}
A real API call in fetchData() might look something more like this
fun fetchData() {
firestoreDB.collection("data")
.document("mydoc")
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val data = task.result.data
processData(data["time"])
}
else {
textLiveData.postValue("ERROR")
}
}
}
The Activity or Fragment that goes along with this doesn't need to know anything about these calls, it just passes actions in by calling methods on the ViewModel and observes the LiveData to update its views when new data is available. It cannot assume that the data is available immediately after a call to fetchData(), but with this pattern it doesn't need to.
The view layer can also do things like show and hide a progress bar while the data is being loaded so the user knows it's working in the background.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val model: MainViewModel by viewModels()
// Observe the LiveData and when it changes, update the
// state of the Views
model.text.observe(this) { processedData ->
binding.text.text = processedData
binding.progress.visibility = View.GONE
}
// When the user clicks the button, pass that action to the
// ViewModel by calling "fetchData()"
binding.getText.setOnClickListener {
binding.progress.visibility = View.VISIBLE
model.fetchData()
}
binding.progress.visibility = View.GONE
}
}
The ViewModel is not strictly necessary for this type of async workflow - here is an example of how to do the same thing in the activity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// When the user clicks the button, trigger the async
// data call
binding.getText.setOnClickListener {
binding.progress.visibility = View.VISIBLE
fetchData()
}
binding.progress.visibility = View.GONE
}
private fun fetchData() {
lifecycleScope.launch {
delay(3000)
val t = Calendar.getInstance().time
processData(t.toString())
}
}
private fun processData(d: String) {
binding.progress.visibility = View.GONE
val p = "The time is $d"
binding.text.text = p
}
}
(and, for completeness, the activity XML)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/text"
android:layout_margin="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="#+id/get_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Get Text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text"
/>
<ProgressBar
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="48dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/get_text"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

What is the type of an async result?

I'm trying to create some coroutines (async) in a loop . I want to start everything in parallel then wait for them all to finish before proceeding. The documentation provides the following example:
coroutineScope {
val deferreds = listOf( // fetch two docs at the same time
async { fetchDoc(1) }, // async returns a result for the first doc
async { fetchDoc(2) } // async returns a result for the second doc
deferreds.awaitAll() // use awaitAll to wait for both network requests
}
but this requires that all the class instantiations be known in advance. However with a varying number of instantiations this is not practical. As a work around I found that the following works:
given a mutable List of class objects from class MyObject and MyObject has a method called myDo()
private val mObjects = mutableListOf<MyObject>()
and ignoring error checking and assuming the list has 2 or more objects then the following works but it's kind of clunky and not very elegant
coroutineScope {
val pd = async { myObjects[0].myDo() }
val dds = mutableListOf(pd)
for (i in 1..numObjects - 1) {
dds.add(async {mObjects[i].myDo() })
}
val nds = dds.toList()
nds.awaitAll()
}// end coroutineScope
What I'd hope to do was something like
val dds = mutableListOf<Job>()
for (i in 0..numObjects - 1) {
dds.add(async {mObjects[i].myDo() })
}
val nds = dds.toList()
nds.awaitAll()
but this doesn't work as the async result is a
Deferred<out T> : Job
interface not a Job interface. The problem with this is in the line
val dds = mutableListOf<Job>()
I don't know what to use in place of Job. That is, for async what is T?
Any help or suggestions would be appreciated
T in this case is whatever type myDo() returns.
I think you are overcomplicating it by creating the extra MutableLists. You can do it like this:
val results = coroutineScope {
mObjects.map { obj ->
async { obj.myDo() }
}.awaitAll()
}
results will be a List<MyDoReturnType>.
Edit: I just realized, since it wasn't obvious to you that the type of a Deferred is whatever the async lambda returns, maybe it's because myDo() doesn't return anything (implicitly returns Unit). If that's the case, you should use launch instead of async. The only difference between them is that async's lambda returns something and launch's doesn't. Deferred inherits from Job because a Deferred is a Job with a result. If myDo() doesn't return anything, your code should look like the following, with no result.
coroutineScope {
for (obj in mObjects) launch { obj.myDo() }
}
The answer from TenFour04 provided the key to my answer The following code works for me
coroutineScope {
val dds = mutableListOf<Deferred<Unit>>()
for (item in mObjects) { dds.add(async {item.myDo() }) }
val nds = dds.toList()
nds.awaitAll()
}
Am I stupid!!! or what. After I figured it out, the answer is almost trivial. The best solution I found is
private val mObjects = mutableListOf<MyObject>()
coroutineScope {val deferreds = listOf(mObjects.size){async{mObjects[it].myDo()}}
deferreds.awaitAll()
}// end coroutineScope
I like this better than the map solution as it doesn't create an intermediate Pair set

Android download multiple files with OkHttp and coroutine

In my app, I get a set of urls to some images from an api and need to create Bitmap objects out of those urls to be able do display the images in the UI. I saw that the android docs recommend using corutines for performing such async tasks, but I am not sure how to do it properly.
Using OkHttp for my http client, I tried the following approach:
GlobalScope.launch {
val gson = Gson();
val parsedRes = gson.fromJson(
response.body?.charStream(),
Array<GoodreadsBook>::class.java
);
// Create the bitmap from the imageUrl
for (i in 0 until parsedRes.size) {
val bitmap =
GlobalScope.async { createBitmapFromUrl(parsedRes[i].best_book.image_url) }
parsedRes[i].best_book.imageBitmap = bitmap.await();
}
searchResults.postValue(parsedRes)
}
Where response is what I get back from my API, and searchResults is a LiveData that hold the parsed response.
Also, here is how I am getting the images from those urls:
suspend fun createBitmapFromUrl(url: String): Bitmap? {
val client = OkHttpClient();
val req = Request.Builder().url(url).build();
val res = client.newCall(req).execute();
return BitmapFactory.decodeStream(res.body?.byteStream())
}
Even though every fetch action is done on a separate coroutine, it's still too slow. Is there a better way of doing it? I can use any other http client if there is one out there optimized for use with coroutines, although I am new to Kotlin so I don't know any.
First of all the createBitmapFromUrl(url: String) does everything synchronously, you've to first stop them from blocking the coroutine thread, you may want to use Dispatchers.IO for that because callback isn't the most idomatic thing ever in coroutines.
val client = OkHttpClient() // preinitialize the client
suspend fun createBitmapFromUrl(url: String): Bitmap? = withContext(Dispatchers.IO) {
val req = Request.Builder().url(url).build()
val res = client.newCall(req).execute()
BitmapFactory.decodeStream(res.body?.byteStream())
}
Now, when you are calling bitmap.await() you are simply saying that "Hey, wait for the deferred bitmap and once it is finished resume the loop for next iteration"
So you may want to do the assignment in the coroutine itself to stop it from suspending the loop, otherwise create another loop for that. I'd go for first option.
scope.launch {
val gson = Gson();
val parsedRes = gson.fromJson(
response.body?.charStream(),
Array<GoodreadsBook>::class.java
);
// Create the bitmap from the imageUrl
for (i in 0 until parsedRes.size) {
launch {
parsedRes[i].best_book.imageBitmap = createBitmapFromUrl(parsedRes[i].best_book.image_url)
}
}
}
Use a library like the following that doesn't use the blocking execute method and instead bridges from the async enqueue.
https://github.com/gildor/kotlin-coroutines-okhttp
suspend fun main() {
// Do call and await() for result from any suspend function
val result = client.newCall(request).await()
println("${result.code()}: ${result.message()}")
}
What this basically does is the following
public suspend fun Call.await(): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
continuation.resume(response)
}
override fun onFailure(call: Call, e: IOException) {
if (continuation.isCancelled) return
continuation.resumeWithException(e)
}
})
continuation.invokeOnCancellation {
try {
cancel()
} catch (ex: Throwable) {
//Ignore cancel exception
}
}
}
}

AsyncTask deprecated from Android R. Any alternatives codes?

Since AsyncTask is deprecated from Android R, i cannot parse or accept a JSON Data from the webhttp://plantplaces.com/perl/mobile/flashcard.pl. So what i did is. I created a kotlin class named DownloadingObject. Below is the code
class DownloadingObject {
#Throws(IOException::class)
fun downloadJSONDataFromLink(link: String): String {
val stringBuilder: StringBuilder = StringBuilder()
val url: URL = URL(link)
val urlConnection = url.openConnection() as HttpURLConnection
try {
val bufferedInputString: BufferedInputStream =
BufferedInputStream(urlConnection.inputStream)
val bufferedReader: BufferedReader =
BufferedReader(InputStreamReader(bufferedInputString))
// temporary string to hold each line read from the BufferedReader.
var inputLineString: String?
inputLineString = bufferedReader.readLine()
while (inputLineString != null) {
stringBuilder.append(inputLineString)
inputLineString = bufferedReader.readLine()
}
} finally {
// regardless of success of Try Block or failure of Try Block, we will disconnect from the URLConnection.
urlConnection.disconnect()
}
return stringBuilder.toString()
}
And i have to run this downloading task in the background. Below is the code
inner class DownloadingPlantTask : AsyncTask>() {
override fun doInBackground(vararg params: String?): List<Plant>? {
// Can access background thread. Not user interface thread
val downloadingObject: DownloadingObject = DownloadingObject()
var jsonData = downloadingObject.downloadJSONDataFromLink(
"http://plantplaces.com/perl/mobile/flashcard.pl"
)
Log.i("JSON", jsonData)
return null
}
Please if anyone can provide any alternative codes. I am just a bieginner in Android development.
There are several ways to achieve multithreading on Android. Since you're using Kotlin you may want to look into Kotlin Coroutines. Some other things out there are the java.concurrent.* package and RxJava, but in my opinion Coroutines are more beginner-friendly and they integrate with Android components very well.
With coroutines, your code would look like this:
#Throws(IOException::class)
suspend fun downloadJSONDataFromLink(link: String): String { ... }
GlobalScope.launch {
val downloadingObject = DownloadingObject()
val jsonData = downloadingObject.downloadJSONDataFromLink("http://plantplaces.com/perl/mobile/flashcard.pl")
Log.i("JSON", jsonData)
}
The suspend keyword means this function can only be called from a coroutine or from another suspending function.
Also you should consider using your Activity/Fragment's lifecycle scope instead of GlobalScope to avoid memory leaks.

Categories

Resources