Activity not updating in tight loop

191 Views Asked by At

I have a situation where I want to update an Activity's text fields as data comes in. The update only occurs when the simulation is completed, not while it is running (takes maybe 2 seconds to run).

Here is the code I have:

    ...
    private var totalLoops = 0
    private val updateDisplayTask = Runnable {
    totalLoopsTV.text = totalLoops.toString()
    totalEmailsSentTV.text = totalEmailsSent.toString()
    totalPushesSentTV.text = totalPushesSent.toString()

    private fun mainLoopFunction(currentTime: Long) {
    ...
      totalLoops++

      if(totalLoops % 20 == 0 || onDeckList.size == 0) {
          Timber.w("UPDATING UI")
          runOnUiThread(updateDisplayTask)
          //handler.post(updateDisplayTask)
      }
    } //end of main loop
     

I've tried both runOnUiThread and handler/post as well as a few other things using Kotlin Coroutines, but nothing so far has worked. Can you see what I'm doing wrong here please? I see the logs of UPDATING UI so I know that the updates do get sent and I do see the last update (the only one I see) at the end.

1

There are 1 best solutions below

2
On

Is this running on another thread, and then you run updateDisplayTask on the main thread? If you're updating totalLoops, totalEmailsSent and totalPushesSent on one thread (this worker thread) and reading them on another (main thread) then because of the way concurrency works, you might not actually see the new values on the main thread.

There are a few ways to manage synchronizing them, but if you're only writing the values on one thread (and you're not massively concerned about the possibility of some of the values changing partway through reading them, so they don't all match up) you can just use the @Volatile annotation on those variables to make them update across threads (works like the volatile keyword in Java).

If you care about atomic updates (everything changing together, can't read or write while something is in the middle of reading or writing them) you'll have to look into some kind of locking, like using synchronized methods and blocks. It's kind of a major (important!) subject, here's a post on it: https://proandroiddev.com/synchronization-and-thread-safety-techniques-in-java-and-kotlin-f63506370e6d