You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.2 KiB

  1. package nova.monadic_sfx.implicits
  2. import scalafx.beans.property.ObjectProperty
  3. import scalafx.beans.property.ReadOnlyObjectProperty
  4. import scalafx.beans.value.ObservableValue
  5. /**
  6. * experimental implicits to be incorporated better later
  7. */
  8. trait MySfxObservableImplicits {
  9. import nova.monadic_sfx.implicits.ExtraObservableImplicits._
  10. implicit def myRichObservable[A, C](
  11. observable: ObservableValue[A, C]
  12. ): MyRichObservable[A, C] = new MyRichObservable(observable)
  13. }
  14. object ExtraObservableImplicits {
  15. final class MyRichObservable[A, C](val self: ObservableValue[A, C])
  16. extends AnyVal {
  17. def filter(f: A => Boolean): ReadOnlyObjectProperty[A] =
  18. Methods.filter(self)(f)
  19. /**
  20. * Simply creates a new observable that mirrors the source observable but
  21. * doesn't emit null values. JavaFX likes to work with null values in scene
  22. * nodes/properties (shrugs) and observables by default emit null values
  23. * that can cause crashes if you forget to null check. ScalaFX does not
  24. * offer any *fixes* for this.
  25. */
  26. def filterNull: ReadOnlyObjectProperty[A] = Methods.filterNull(self)
  27. }
  28. }
  29. object Types {
  30. type Observable[A] = ObservableValue[A, _]
  31. }
  32. object Methods {
  33. import Types._
  34. def filter[B](
  35. a: Observable[B]
  36. )(f: B => Boolean): ReadOnlyObjectProperty[B] = {
  37. val prop = ObjectProperty[B](a.value)
  38. def changeHandler() =
  39. prop.synchronized {
  40. if (f(a.value)) {
  41. prop.value = a.value
  42. }
  43. }
  44. a onChange changeHandler()
  45. prop
  46. }
  47. /**
  48. * Simply creates a new observable that mirrors the source observable but
  49. * doesn't emit null values. JavaFX likes to work with null values in scene
  50. * nodes/properties (shrugs) and observables by default emit null values
  51. * that can cause crashes if you forget to null check. ScalaFX does not
  52. * offer any *fixes* for this.
  53. *
  54. * @param a
  55. * @return
  56. */
  57. def filterNull[B](
  58. a: Observable[B]
  59. ): ReadOnlyObjectProperty[B] = {
  60. val prop = ObjectProperty[B](a.value)
  61. def changeHandler() =
  62. prop.synchronized {
  63. if (a.value != null) {
  64. prop.value = a.value
  65. }
  66. }
  67. a onChange changeHandler()
  68. prop
  69. }
  70. }