Async.kt 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package io.r_a_d.radio2
  2. import android.os.AsyncTask
  3. import android.util.Log
  4. import io.r_a_d.radio2.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. 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. }
  23. private fun resetPlayerStateOnNetworkError() {
  24. var storeReset = false
  25. // checking isInitialized avoids setting streamerName multiple times, so it avoids a callback loop.
  26. if (PlayerStore.instance.isInitialized)
  27. {
  28. PlayerStore.instance.currentSong.artist.postValue("")
  29. PlayerStore.instance.isInitialized = false
  30. PlayerStore.instance.streamerName.postValue("")
  31. PlayerStore.instance.queue.clear()
  32. PlayerStore.instance.lp.clear()
  33. PlayerStore.instance.isQueueUpdated.postValue(true)
  34. PlayerStore.instance.isLpUpdated.postValue(true)
  35. // safe-update for the title avoids callback loop too.
  36. if (PlayerStore.instance.currentSong.title.value != noConnectionValue)
  37. PlayerStore.instance.currentSong.title.postValue(noConnectionValue)
  38. storeReset = true
  39. }
  40. Log.d(tag, "fallback for no network. Store reset : $storeReset")
  41. }
  42. override fun doInBackground(vararg params: Any?): Any? {
  43. try {
  44. return handler(parameters)
  45. } catch (e: Exception) {
  46. Log.d(tag,e.toString())
  47. onException(e)
  48. }
  49. return null
  50. }
  51. override fun onPostExecute(result: Any?) {
  52. try {
  53. post(result)
  54. } catch (e: Exception) {
  55. Log.d(tag,e.toString())
  56. onException(e)
  57. }
  58. }
  59. }