-
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.
Merge pull request #20937 from wordpress-mobile/hackweek/database-anr
[Hack Week] A generic solution for resolving the ANRs caused by accessing local database
- Loading branch information
Showing
2 changed files
with
73 additions
and
36 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
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,33 @@ | ||
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 | ||
* @see <a href="https://github.com/wordpress-mobile/WordPress-Android/pull/20937">Introduction</a> | ||
*/ | ||
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) | ||
} | ||
} | ||
|
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