SoFunction
Updated on 2025-04-14

Complete solution to implement multi-threaded data refresh in Kotlin

The complete solution to implement multi-threaded data refresh in Kotlin is as follows:

1. Basic thread refresh plan

Using Handler Message Message Message
After the child thread executes a time-consuming task,HandlerSend a message to the main thread to update the UI‌:

// Main thread definitionHandler private val handler = object : Handler(())
{ 
override fun handleMessage(msg: Message)
{ 
when () 
{ 
1 ->  = () 
}
}
}
// The child thread sends a messagethread { val data = fetchData() 
// Time-consuming operationval msg = ().apply 
{ 
what = 1 obj = data
} 
(msg) 
}

runOnUiThread simplifies operation
Switch directly to the main thread update UI in Activity:

thread 
{
    val result = processData() runOnUiThread
    { 
         = result 
    } 
}

2. Coroutine and Flow Solution (recommended)

Coroutines are refreshed asynchronously
Use coroutines to switch thread contexts to avoid direct thread operation‌:

()
{ 
    val data = () 
    withContext() 
    { 
         = data
    }
    }

Flow periodically refreshes automatically
passflowImplement timed data refresh:

fun tickerFlow(period: Duration) = flow 
{
    while (true)
    { 
        emit(Unit) delay(period) 
    } 
} 
// Trigger in ViewModel{ 
    tickerFlow((5)) .collectLatest
    { 
        _ -> val newData = fetchData() _uiState.value = (newData) 
    }
    }

3. LiveData integration solution ‌

Automatic updates in combination with LiveData
Pass in ViewModelLiveDataDriver UI refresh:

class MyViewModel : ViewModel() {
 private val _data = MutableLiveData<String>() 
val data: LiveData<String> = _data 
   fun refresh() {
   () { 
   val result = fetchData() _data.postValue(result) 
     }
   }
 } 
// Observation in Activity (this) {
  = it 
}

4. Things to note

  • Thread safety‌: It is prohibited to operate UI controls directly on child threads (such as()), must be switched back to the main thread‌
  • Resource releaseexistonDestroy()Cancel the coroutine or clear the Handler message queue to avoid memory leaks‌
  • Performance optimization‌: It is recommended to use high-frequency refreshFloworLiveData, avoid frequent thread creation‌

The coroutine + Flow/LiveData combination solution is recommended first. The traditional Handler solution is suitable for low-version compatible scenarios.

This is the end of this article about implementing multi-threaded data refresh in Kotlin. For more related content on Kotlin multi-threaded data refresh, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!