During development process of an Android app I have come across this design puzzle I am not able to solve at the moment. I would appreciate any thoughts, workaround or clean solution :) I ll try to simplify it as much as possible:
Everything starts with a common overver pattern implementation. There is a subject which changes states upon its public method invokations; and there are observers which reacts accordingly to this changes. In this case, the subject is a STATEFUL subject, which means it has an internal state controller (an int) which changes like an automata. Each time its state changes it notifies to the observers as usual:
- client -> subject.anyMethod() //changes subject state to state X
- subject -> notifyObservers(newState) // subject notifies new state X
- observer -> subject.getData() // retrieves data
But now think on this situation:
- client -> subject.anyMethod() //changes subject state to state X
- subject -> notifyObservers(X) // subject FIRST notification waterfall
- observerA -> subject.anyMethod() //changes subject to state Y
- subject -> notifyObservers(Y) // start a SECOND notify waterfall
What is going to happen now as a result of the SECOND waterfall is that next observers(lets say observerB) is gonna receive its notification as state Y (from this last second waterfall), act accordingly and when this SECOND waterfall finish the PC (program counter) is gonna continue with the FIRST notification waterfall and renotify to observerB the OLD STATE X. This generates two main issues: first one the observerB gets notified of the new states in wrong order (first state Y and then state X when it should be the opposite way) and second and most important, even being notified in wrong order, when the observerB receives the notification of the new state X it is totally WRONG as the subject real state is Y; and this generates a lot of issues.
As you might have realized, this happens when an observer commits a change in the state of the subject when it gets notified instead of only gettind data from the subject. I would appreciate any other pattern or solution. Also clarify there is only one thread.
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire