1

Here's the situation, I am building an SDK for customers to be notified of three different touch states:

  1. Object Touched

  2. Object Touched Outside

  3. Object Touched Exit

I tried using the Observer Design Pattern, where the Observable sends updates to all the Observers which are the customers. however there are a few problems.

https://stonesoupprogramming.com/2017/10/28/observer-pattern-in-kotlin/

Following this design guideline is see that in order for customers to subscribe they will need to code the following:

val bob = Bob()
bob.addObserver(Customer1())



 class Customer1: Observer{

    val name = "Customer1"

    override fun update(o: Observable?, arg: Any?) {
      // Do your logic here
    }
}

This means customer when they integrate the SDK need to both declare a Class file called Customer1 with extended Observer.

Is there a way to simplify the process of having customers register as an Observer for our SDK's Observable? I'm not sure what sort of abstraction to implement.

Mysterious_android
  • 598
  • 2
  • 9
  • 32
  • 1
    I don't know Kotlin but the point of the pattern is it gives you the ability to register any number and types of observers. Any Observer can be updated with and by any Observable. To consume your API, the client needs to deal with that. That doesn't mean they need a `Customer` class necessarily. It just means they need an Observer that knows how to deal with the data (`arg`) you're passing. As in your link, you could even inspect the type and deal with multiple Observable types with one `update` if need be. – ChiefTwoPencils Jul 01 '19 at 01:33
  • 1
    Thanks @ChiefTwoPencils I think the easier route would be to implement an [event listener](https://stackoverflow.com/questions/6270132/create-a-custom-event-in-java) instead as it removes all the previous boiler plate code as seen in my Observer example – Mysterious_android Jul 01 '19 at 01:50
  • 1
    You can give `PublishSubject` a try – Bach Vu Jul 01 '19 at 04:03
  • Why you don't want to use LiveData? – Edhar Khimich Jul 01 '19 at 05:26
  • @EdgarKhimich i thought LiveData is for observing an Activity UI change while there is no UI in this case. – Mysterious_android Jul 18 '19 at 02:50
  • @Mysterious_android LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. More clean is here: https://medium.com/@elye.project/understanding-live-data-made-simple-a820fcd7b4d0 – Edhar Khimich Jul 18 '19 at 15:01

1 Answers1

0

Pub/Sub is also another option. Publish events and other areas of code can subscribe/listen to them, and react or respond.

Urasquirrel
  • 1,461
  • 1
  • 18
  • 34