-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create an alternative of AsyncTask for handling thread-switching requ…
…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.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
WordPress/src/main/java/org/wordpress/android/datasets/AsyncTaskHandler.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
|