Async.kt 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package fr.riff_app.riff
  2. import android.os.AsyncTask
  3. import android.util.Log
  4. import fr.riff_app.riff.playerstore.PlayerStore
  5. class Async(val handler: (Any?) -> Any?, val post: (Any?) -> Unit = {},
  6. private val actionOnError: ActionOnError = ActionOnError.RESET, private val parameters: Any? = null) :
  7. AsyncTask<Any, Void, Any>() {
  8. init {
  9. try {
  10. execute()
  11. } catch (e: Exception)
  12. {
  13. //[REMOVE LOG CALLS]Log.d(tag,e.toString())
  14. }
  15. }
  16. private fun onException(e: java.lang.Exception) {
  17. when(actionOnError)
  18. {
  19. ActionOnError.RESET -> resetPlayerStateOnNetworkError()
  20. ActionOnError.NOTIFY -> return
  21. }
  22. e.printStackTrace()
  23. }
  24. private fun resetPlayerStateOnNetworkError() {
  25. var storeReset = false
  26. // checking isInitialized avoids setting streamerName multiple times, so it avoids a callback loop.
  27. if (PlayerStore.instance.isInitialized)
  28. {
  29. PlayerStore.instance.currentSong.artist.postValue("")
  30. PlayerStore.instance.isInitialized = false
  31. PlayerStore.instance.streamerName.postValue("")
  32. PlayerStore.instance.queue.clear()
  33. PlayerStore.instance.lp.clear()
  34. PlayerStore.instance.isQueueUpdated.postValue(true)
  35. PlayerStore.instance.isLpUpdated.postValue(true)
  36. // safe-update for the title avoids callback loop too.
  37. if (PlayerStore.instance.currentSong.title.value != noConnectionValue)
  38. PlayerStore.instance.currentSong.title.postValue(noConnectionValue)
  39. storeReset = true
  40. }
  41. //[REMOVE LOG CALLS]Log.d(tag, "fallback for no network. Store reset : $storeReset")
  42. }
  43. override fun doInBackground(vararg params: Any?): Any? {
  44. try {
  45. return handler(parameters)
  46. } catch (e: Exception) {
  47. //[REMOVE LOG CALLS]Log.d(tag,e.toString())
  48. onException(e)
  49. }
  50. return null
  51. }
  52. override fun onPostExecute(result: Any?) {
  53. try {
  54. post(result)
  55. } catch (e: Exception) {
  56. //[REMOVE LOG CALLS]Log.d(tag,e.toString())
  57. onException(e)
  58. }
  59. }
  60. }