SharedData.kt 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package eu.kanade.tachiyomi.util
  2. import java.util.HashMap
  3. /**
  4. * This singleton is used to share some objects within the application, useful to communicate
  5. * different parts of the app.
  6. *
  7. * It stores the objects in a map using the type of the object as key, so that only one object per
  8. * class is stored at once.
  9. */
  10. object SharedData {
  11. /**
  12. * Map where the objects are saved.
  13. */
  14. val map = HashMap<Class<*>, Any>()
  15. /**
  16. * Publish an object to the shared data.
  17. *
  18. * @param data the object to put.
  19. */
  20. fun <T : Any> put(data: T) {
  21. map[data.javaClass] = data
  22. }
  23. /**
  24. * Retrieves an object from the shared data.
  25. *
  26. * @param classType the class of the object to retrieve.
  27. * @return an object of type T or null if it's not found.
  28. */
  29. @Suppress("UNCHECKED_CAST")
  30. fun <T : Any> get(classType: Class<T>) = map[classType] as? T
  31. /**
  32. * Removes an object from the shared data.
  33. *
  34. * @param classType the class of the object to remove.
  35. * @return the object removed, null otherwise.
  36. */
  37. fun <T : Any> remove(classType: Class<T>) = get(classType)?.apply { map.remove(classType) }
  38. /**
  39. * Returns an object from the shared data or introduces a new one with the given function.
  40. *
  41. * @param classType the class of the object to retrieve.
  42. * @param fn the function to execute if it didn't find the object.
  43. * @return an object of type T.
  44. */
  45. @Suppress("UNCHECKED_CAST")
  46. inline fun <T : Any> getOrPut(classType: Class<T>, fn: () -> T) = map.getOrPut(classType, fn) as T
  47. }