Skip to content

Commit

Permalink
Create an alternative of AsyncTask for handling thread-switching requ…
Browse files Browse the repository at this point in the history
…irements
  • Loading branch information
Jarvis Lin committed Jun 4, 2024
1 parent 56f0686 commit 83c6a66
Showing 1 changed file with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.wordpress.android.datasets

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
* Helper class to handle async tasks by using coroutines
*/
object AsyncTaskHandler {
/**
* Load data in the background and handle the result on the main thread
*/
@JvmStatic
fun <T> load(backgroundTask: () -> T, callback: AsyncTaskCallback<T>) {
CoroutineScope(Dispatchers.IO).launch {
// handle the background task
val result = backgroundTask()

withContext(Dispatchers.Main) {
// handle the result on the main thread
callback.onTaskFinished(result)
}
}
}

interface AsyncTaskCallback<T> {
fun onTaskFinished(result: T)
}
}

0 comments on commit 83c6a66

Please sign in to comment.