changeset 33:bead5d7e8c69

Deal with constipated read tasks.
author David Barts <n5jrn@me.com>
date Sat, 27 Feb 2021 19:27:07 -0800
parents be08576794af
children 19c584b29679
files app/src/main/java/com/bartsent/simpleresizer/EditImage.kt
diffstat 1 files changed, 18 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/app/src/main/java/com/bartsent/simpleresizer/EditImage.kt	Fri Feb 26 14:26:50 2021 -0800
+++ b/app/src/main/java/com/bartsent/simpleresizer/EditImage.kt	Sat Feb 27 19:27:07 2021 -0800
@@ -29,11 +29,14 @@
 import com.bartsent.simpleresizer.lib.getScaledInstance
 import java.io.File
 import java.io.IOException
+import java.util.concurrent.Callable
+import java.util.concurrent.Future
 
 class EditImage : AppCompatActivity() {
     class State: ViewModel() {
         var uri: Uri? = null
         var bitmap: Bitmap? = null
+        var reader: Future<Unit>? = null
     }
     private lateinit var viewModel: State
 
@@ -112,7 +115,7 @@
         if (imageUri != viewModel.uri) {
             viewModel.uri = imageUri
             binding.progressBar.visibility = ProgressBar.VISIBLE
-            ThreadPools.WORKERS.execute {
+            viewModel.reader = ThreadPools.WORKERS.submit(Callable<Unit> {
                 val newBitmap = contentResolver.openInputStream(imageUri).use {
                     BitmapFactory.decodeStream(it)
                 }
@@ -122,8 +125,9 @@
                         showFatalError(getString(R.string.error_bad_image))
                     else
                         setImage(newBitmap)
+                    viewModel.reader = null
                 }
-            }
+            })
             return
         }
 
@@ -133,6 +137,18 @@
             setImage(oldBitmap)
     }
 
+    override fun onDestroy() {
+        // Read tasks may get badly constipated, since the image may well be on
+        // cloud server like Google Pictures. So be sure to terminate any active
+        // read task with extreme prejudice.
+        val reader = viewModel.reader
+        if (reader != null) {
+            reader.cancel(true)
+            viewModel.reader = null
+        }
+        super.onDestroy()
+    }
+
     private fun setImage(image: Bitmap): Unit {
         binding.imageSize.text = getString(R.string.image_size_text, image.width, image.height)
         binding.image.setImageBitmap(image)