I have a class that goes to decrease the image but I’m currently on AsyncTask, now I want to replace it because AsyncTask is now deprecated.So can someone help me out with a workaround
Here is my code:
class DecreaseImageTask( val uri: Uri? = null, val bitmap: Bitmap? = null, var context: Context, var listener: (String?) -> Unit ) : AsyncTask<Void, Long, String?>() { override fun doInBackground(vararg params: Void?): String? { return when { uri != null -> { decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "") } bitmap != null -> { decreaseImageSize(bitmap = bitmap) } } } override fun onPostExecute(result: String?) { super.onPostExecute(result) listener(result) } }
Advertisement
Answer
You could change your decreaseImageSize
to accept a callback as a parameter.
In this case, the function will no longer need to return a string, which is passed as a parameter to the callback function and then used as
a parameter in its body:
fun decreaseImageSize(imagePath: String? = null, bitmap: Bitmap? = null, callback: (String) -> Unit) { ... val result = "" // The result of the previous decreaseImageSize function callback(result) }
Then, instead of calling the AsyncTask
use the new decreaseImageSize
function:
decreaseImageSize(imagePath = FileUtils.getPathURI(context, uri) ?: "") { result -> // Execute the code after the image is decreased } decreaseImageSize(bitmap = bitmap) { result -> // Execute the code after the image is decreased }