-
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.
- Loading branch information
Jarvis Lin
committed
Jun 10, 2024
1 parent
4384b1b
commit e5866cb
Showing
3 changed files
with
55 additions
and
38 deletions.
There are no files selected for viewing
35 changes: 0 additions & 35 deletions
35
WordPress/src/main/java/org/wordpress/android/datasets/AsyncIoTaskExecutor.kt
This file was deleted.
Oops, something went wrong.
51 changes: 51 additions & 0 deletions
51
WordPress/src/main/java/org/wordpress/android/datasets/AsyncTaskExecutor.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,51 @@ | ||
package org.wordpress.android.datasets | ||
|
||
import kotlinx.coroutines.CoroutineDispatcher | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.withContext | ||
|
||
/** | ||
* Helper class to handle asynchronous I/O tasks using coroutines | ||
* @see <a href="https://github.com/wordpress-mobile/WordPress-Android/pull/20937">Introduction</a> | ||
*/ | ||
object AsyncTaskExecutor { | ||
/** | ||
* Execute a data loading task in the IO thread and handle the result on the main thread | ||
*/ | ||
@JvmStatic | ||
fun <T> executeIo(scope: CoroutineScope, backgroundTask: () -> T, callback: AsyncTaskCallback<T>) { | ||
execute(scope, Dispatchers.IO, backgroundTask, callback) | ||
} | ||
|
||
/** | ||
* Execute a data loading task in the default thread and handle the result on the main thread | ||
*/ | ||
@JvmStatic | ||
fun <T> executeDefault(scope: CoroutineScope, backgroundTask: () -> T, callback: AsyncTaskCallback<T>) { | ||
execute(scope, Dispatchers.Default, backgroundTask, callback) | ||
} | ||
|
||
private fun <T> execute( | ||
scope: CoroutineScope, | ||
dispatcher: CoroutineDispatcher, | ||
backgroundTask: () -> T, | ||
callback: AsyncTaskCallback<T> | ||
) { | ||
scope.launch(dispatcher) { | ||
// 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) | ||
} | ||
} | ||
|
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