Reactive observable that captures onrendered state changes (in scalajs / js) - reactive-programming

I am working with a library (ScalaJS and react specifically) where I have an interesting situation that I assume is pretty routine for an experienced reactive-programmer. I have a Component with State and a callback shouldComponentUpdate(State). The basic idea here is that certainly if the callback is triggered but the State has not changed from the last render, returnfalse. Otherwise, perhaps return true if the State change matters.
I am using a library monix but it seems identical to other reactive libraries so I would imagine this is a fairly context-independent question.
I would like to do something like: have some state that reflects the deltas of State since the last render. On each render, clear the buffer. Or, have a renderedState subject that reflects all rendered states as a sequence, a receivedState subject that reflects all received State updates, and a needsUpdate subject that reflects whether the latest receivedState matches the latest renderedState. I am having trouble actually executing these ideas, though. Here is where I am stuck at:
Here is what I've done for other callbacks:
lazy val channel_componentWillUpdate = channel_create[ComponentWillUpdate[Props, State, ResponsiveLayoutContainerBackend, TopNode]]
def componentWillUpdate(cwupd: ComponentWillUpdate[Props, State, ResponsiveLayoutContainerBackend, TopNode]) =
Callback {
channel_componentWillUpdate.onNext(cwupd)
}
So when then componentWillUpdate callback is triggered, the handler fires onNext on the channel (subject).
The shouldComponentUpdate is different though. It returns a value, so it needs to be structured differently. I am having trouble thinking of the right adjustment.
To summarize a bit:
react has callbacks at different stages of the view lifecycle, like componentDidMount, componentDidUpdate, etc.
I am handling all but one stage the same way - the shape of the callback is State -> Callback<Void> so alls I have to do is use a Subject for each type of lifecycle event and submit its onNext when the callback is triggered.
But one type of event has shape either State -> Boolean or State -> Callback<Boolean>.
I feel like I should be able to model this with a subject representing the delta between the last state rendered/received.
However, I don't know how this fits into the reactive style.

Related

Where to perform state changes with Clean Architecture in Flutter?

When using Clean Architecture with flutter we see a diagram similar to this:
(I wrote MobX package as an example, but it could be anything like BLoC, Redux...)
I may have a problem with this diagram since the Store resides in presentation layer and is responsible for changing the state.
Imagine that the app loads a list of todos through a method called "getTodos" implementend in TodosStore.
The "getTodos" implementation might be:
_state = State.loading();
final result = GetTodos();
_state = State.done();
(I oversimplified things)
It starts by updating the state to loading, calls a use case returning the list and set state to done.
The problems I found here:
Stores are responsible for calling UC, updating state, handling errors...
Use case is simply a bridge and does not handle the business logic
This is a rather simple example.
But let's imagine that I have a view with 3 lists of differents data (it may be an absurd example).
The view interacts with 3 differents stores. There's a button in an app bar. Its goal is to clear the 3 lists.
How to achieve that behavior ?
The button onPressed method will need to call "clearData" for each store
The "clear" method of each store will simply updates its properties
The thing is that the view is not as dumb as we wanted.
The store is not even interacting with any use case
Should a ClearLists use case be legitimate here?
Since I do not like having much logic in presentation layer, I tend to follow this diagram:
Each view has its own ViewModel. The VM simply interacts with the Use Case. These UC may or may not return a value. For instance: my UC is a ValidateNumberRange, I might not interact with a store. It makes sense to return a bool. But if my UC is a ClearTodoList, it might interact with a store. The success or failure may be a stored value. That way returning a value may not be useful.
With this new diagram, the "GetTodos" use case callable method implementation might be:
store.set(State.loading());
final result = repo.getTodos();
result.fold(
(failureMsg) { store.set(State.failure(failureMsg)); },
(newList) { store.set(State.done(newList)); },
);
Use case handles the state management logic
The View calls a VM method. The VM calls a UC and observe changes in Store (through MobX here)
I ask myself a ton of questions:
Did I correctly understand the role of UC in clean architecture ?
Is changing state (to loading, done, failure) considered business logic ?
Where would you put state management solution in your app ?
I look forward to hear your thoughts
Use cases encapsulate business rules, and they are platform-agnostic and delivery-mechanism-agnostic (e.g. UI).
Use Cases are based on functionality, but without implementation details.
Book:
https://dannorth.net/introducing-bdd
changing state is responsibility of presentation layer; Presentation Layer != UI Layer
Think as like this:
Domain Layer <= infrastructure layer <= application layer <= presentation layer <= UI Layer
the dependencies always should be inward.
imagine like this: Side effects free business logic (functional core) is always in center and the rest (stateful elements, UI, frameworks) surround it.
from your diagram:
AppState and ViewModel always reside in presentation layer. Flutter specific classes are belongs to the UI.

Is There a Plan For Relaxing JavaFX Property Update Rules Outside the Application FX Thread?

I have a working JavaFX application. It has three main parts:
A list of signals visible globally to the entire application. Each signal has a String value property that is observable. This list is instantiated before the JavaFX scene is constructed, the signal list constructor is run in the Application FX thread.
A JavaFX table implemented as an Observable Array List so that as signal values change they are automatically updated on the GUI.
A simulation engine that runs a loop that changes signal values. This loop is run in a worker thread.
I am fully aware that GUI elements like selection lists, text in boxes, etc. can only be updated in the Application FX thread. I use Platform.runLater(someRunnableThing) to do that. However, what blindsided me was that even changing a signal value, which changes the value of the observable String property, must be done in the FX thread or not-in-Application-FX-thread exceptions will be thrown.
Curiously the application still works fine despite these exceptions, because eventually (instantaneously to a human observer) the changed value is picked up and displayed. I only noticed this when doing final checks of run-time behavior before release.
It is a very common thing for a worker thread to be changing variables in the background while a GUI is displaying information based on the changing variables. Platform.runLater() is expensive and somewhat non-deterministic. Since the worker thread is not touching the GUI and the application FX thread can choose to grab updates whenever it wants it seems draconian to me for Java to force this behavior.
Have I missed something about modifying observed properties? Any thoughts and ideas appreciated.
There are no rules about updating JavaFX properties from background threads. The only rule is that you cannot update nodes that are part of a scene graph from a background thread, and there are no plans (and likely never will be) to relax that rule.
You didn't post any code, so we can only make educated guesses as to what the actual problem is. What is likely happening is that you have a listener or a binding on one of the properties (or observable collections) that is being changed from your background thread, where the listener/binding is updating the UI. Listeners with observables (including listeners created and registered by bindings) are, of course, invoked on the same thread on which the observable is changed.
So if you have something like
someApplicationProperty.addListener((obs, oldValue, newValue) -> {
someUIElement.setSomeValue(...);
});
or perhaps
someUIElement.someProperty().bind(someApplicationProperty);
just replace it with
someApplicationProperty.addListener((obs, oldValue, newValue) -> {
Platform.runLater(() -> someUIElement.setSomeValue(...));
});
In other words, you can continue to update your application properties from the background thread, as long as your listener updates the UI from the FX Application Thread.
In the case where the listener is registered by the UI component itself, you must ensure that the observable with which the listener is registered is changed on the UI thread. This is the case in the example you allude to, for example updating the backing list for a ListView or TableView. You can do this either by directly invoking Platform.runLater(), or by placing a layer in between the model and the UI. For the latter approach, see Correct Way to update Observable List from background thread
Also maybe see http://www.oracle.com/technetwork/articles/java/javafxinteg-2062777.html

When is onTransition codes executed, exactly? -- Akka, FSM

I have a doubt whether the code in the "onTransition" block (akka FSM) is executed after the new state is reached? or before the new state is reached.
The articles and book I've read mentions the word "during"... which (to me) suggests "before the new state is reached".
Does it really matter?
I guess so... I mean, changing to a new state implies (in most cases) changing the state data. Usually we would change that state data in the event handler (in the "when-case-event" block).
But what if the new state depends on the outcome of calculations / actions performed in the "onTransition" block? In that case, we will have to move that block into the "when-case-event" block.
So, it's not clear for me now...: is there any rule / guidance: what actions should go into the "when-case-event", and what actions should go into the "onTransition"?
addition: I hope in the next revision of Akka Doc, some kind of clarification / guidance on this topic would be included.
Thanks in advance,
Raka
In onTransition the old state data is available via stateData, and the new state data is available as nextStateData. The new state cannot be changed by onTransition, but you can send a message to self.

What is the difference between hook and callback?

By reading some text, especially the iOS document about delegate, all the protocol method are called hook that the custom delegate object need to implement. But some other books, name these hook as callback, what is the difference between them? Are they just different name but the same mechanism? In addition to Obj-C, some other programming languages, such as C, also got the hook, same situation with Obj-C?
The terminology here is a bit fuzzy. In general the two attempt to achieve similar results.
In general, a callback is a function (or delegate) that you register with the API to be called at the appropriate time in the flow of processing (e.g to notify you that the processing is at a certain stage)
A hook traditionally means something a bit more general that serves the purpose of modifying calls to the API (e.g. modify the passed parameters, monitor the called functions). In this meaning it is usually much lower level than what can be achieved by higher-level languages like Java.
In the context of iOS, the word hook means the exact same thing as callback above
Let me chime in with a Javascript answer. In Javascript, callbacks, hooks and events are all used. In this order, they are each higher level concepts than the other.
Unfortunately, they are often used improperly which leads to confusion.
Callbacks
From a control flow perspective, a callback is a function, usually given as an argument, that you execute before returning from your function.
This is usually used in asynchoronous situations when you need to wait for I/O (e.g. HTTP request, a file read, a database query etc.). You don't want to wait with a synchronous while loop, so other functions can be executed in the meantime.
When you get your data, you (permanently) relinquish control and call the callback with the result.
function myFunc(someArg, callback) {
// ...
callback(error, result);
}
Because the callback function may be some code that hasn't been executed yet, and you don't know what's above your function in the call stack, generally instead of throwing errors you pass on the error to the callback as an argument. There are error-first and result-first callback conventions.
Mostly callbacks have been replaced by Promises in the Javascript world and since ES2017+, you can natively use async/await to get rid of callback-rich spaghetti code and make asynchronous control flow look like it was synchronous.
Sometimes, in special cascading control flows you run callbacks in the middle of the function. E.g. in Koa (web server) middleware or Redux middleware you run next() which returns after all the other middlewares in the stack have been run.
Hooks
Hooks are not really a well-defined term, but in Javascript practice, you provide hooks when you want a client (API/library user, child classes etc.) to take optional actions at well-defined points in your control flow.
So a hook may be some function (given as e.g. an argument or a class method) that you call at a certain point e.g. during a database update:
data = beforeUpdate(data);
// ...update
afterUpdate(result);
Usually the point is that:
Hooks can be optional
Hooks usually are waited for i.e. they are there to modify some data
There is at most one function called per hook (contrary to events)
React makes use of hooks in its Hooks API, and they - quoting their definition - "are functions that let you “hook into” React state and lifecycle features", i.e. they let you change React state and also run custom functions each time when certain parts of the state change.
Events
In Javascript, events are emitted at certain points in time, and clients can subscribe to them. The functions that are called when an event happens are called listeners - or for added confusion, callbacks. I prefer to shun the term "callback" for this, and use the term "listener" instead.
This is also a generic OOP pattern.
In front-end there's a DOM interface for events, in node.js you have the EventEmitter interface. A sophisticated asynchronous version is implemented in ReactiveX.
Properties of events:
There may be multiple listeners/callbacks subscribed (to be executed) for the same event.
They usually don't receive a callback, only some event information and are run synchronously
Generally, and unlike hooks, they are not for modifying data inside the event emitter's control flow. The emitter doesn't care 'if there is anybody listening'. It just calls the listeners with the event data and then continues right away.
Examples: events happen when a data stream starts or ends, a user clicks on a button or modifies an input field.
The two term are very similar and are sometimes used interchangably. A hook is an option in a library were the user code can link a function to change the behavior of the library. The library function need not run concurrent with the user code; as in a destructor.
A callback is a specific type of hook where the user code is going to initiate the library call, usually an I/O call or GUI call, which gives contol over to the kernel or GUI subsystem. The controlling process then 'calls back' the user code on an interupt or signal so the user code can supply the handler.
Historically, I've seen hook used for interupt handlers and callback used for GUI event handlers. I also see hook used when the routine is to be static linked and callback used in dynamic code.
Two great answers already, but I wanted to throw in one more piece of evidence the terms "hook" and "callback" are the same, and can be used interchangeably: FreeRTOS favors the term "hook" but recognizes "callback" as an equivalent term, when they say:
The idle task can optionally call an application defined hook (or callback) function - the idle hook.
The tick interrupt can optionally call an application defined hook (or callback) function - the tick hook.
The memory allocation schemes implemented by heap_1.c, heap_2.c, heap_3.c, heap_4.c and heap_5.c can optionally include a malloc() failure hook (or callback) function that can be configured to get called if pvPortMalloc() ever returns NULL.
Source: https://www.freertos.org/a00016.html

What do the various ISubject implementations do and when would they be used?

I have a fairly good idea of what the Subject class does and when to use it, but I've just been looking through the language reference on msdn and see there are various other ISubject implementations such as:
AsyncSubject
BehaviorSubject
ReplaySubject
As the documentation is pretty thin on the ground, whats the point of each of these types and under what situations would you use them?
These subjects all share a common property - they take some (or all) of what gets posted to them via OnNext and record it and play it back to you - i.e. they take a Hot Observable and make it Cold. This means, that if you Subscribe to any of these more than once (i.e. Subscribe => Unsubscribe => Subscribe again), you'll see at least one of the same value again.
ReplaySubject: Every time you subscribe to the Subject, you get the entire history of what has been posted replayed back to you, as fast as possible (or a subset, like the last n items)
AsyncSubject: Always plays back the last item posted and completes, but only after the source has completed. This Subject is awesome for async functions, since you can write them without worrying about race conditions: even if someone Subscribes after the async method completes, they get the result.
BehaviorSubject: Kind of like ReplaySubject but with a buffer of one, so you always get the last thing that was posted. You also can provide an initial value. Always provides one item instantly on Subscribe.
In light of the latest version (v1.0.2856.0) and to keep this question up to date, there has been a new set of subject classes:
FastSubject, FastBehaviorSubject, FastAsyncSubject and FastReplaySubject
As per the release notes they
are much faster than regular subjects
but:
don’t decouple producer and consumer by an IScheduler
(effectively limiting them to
ImmediateScheduler);
don’t protect against stack overflow;
don’t synchronize input messages.
Fast subjects are used by Publish and
Prune operators if no scheduler is
specified.
In regards to AsyncSubject
This code:
var s = new AsyncSubject<int>();
s.OnNext(1);
s.Subscribe(Console.WriteLine);
s.OnNext(2);
s.OnNext(3);
s.OnCompleted();
prints a single value 3. And it prints same if subscription is moved to after completion. So it plays back not the first, but the last item, plays it after completion (until complete, it does not produce values), and it does not work like Subject before completion.
See this Prune discussion for more info (AsyncSubject is basically the same as Prune)
Paul's answer pretty much nails it. There's a few things worth adding, though:
AsyncSubject works as Paul says, but only after the source completes. Before that, it works like Subject (where "live" values are received by subscribers)
AsyncSubject has changed since I last ran tests against it. It no longer acts as a live subject before completion, but waits for completion before it emits a value. And, as Sergey mentions, it returns the last value, not the first (though I should have caught that as that's always been the case)
AsyncSubject is used by Prune, FromAsyncPattern, ToAsync and probably a few others
BehaviorSubject is used by overloads of Publish that accept an initial value
ReplaySubject is used by Replay
NOTE: All operator references above refer to the publishing set of operators as they were before they were replaced with generalised publish operators in rev 2838 (Christmas '10) as it has been mentioned that the original operators will be re-added