I have a type that receives data through websocket / event and it instantiates a couple other types that also need that data for their work.
I thought it would simplify the code to have only one event listener, in the parent type and pass the result by reference so the children types could access the last data.
I've never used byref in F# and .. looks like I don't get it right
From the parent:
let mutable lastTrade = TradeData.empty // this gets updated through an event
let closeOrderHandler = CloseOrderHandler(coreGuid, instrument, &lastTrade)
and the child object:
type CloseOrderHandler(coreGuid: string, instrument: Instrument, lastTrade: byref<TradeData>) = ...
but this will not compile, I get:
[FS0412] A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
what am I doing wrong?
What I am trying to accomplish is to have one mutable field with results updated by a socket / event and the child types be able to read the last result as they need (their actions are event driven, so they don't always get called from the parent and need to access the latest value as they need).
Related
I need to implement an abstract class function, which own a an specific data type. But I need inside my logic layer to make the attribute which is going to be passed as a dynamic data type. But when i Pass it to the function, i am sure that its data type will be as needed. So, i type (product.value.pickedImages) as ListOf5) . But it does an Exception.
The Abstract Class Code Is:
Future<Either<FireStoreServerFailures, List<String>>> uploadProductImages(
{required ListOf5<File> images});
The Implementation Code Is:
Future<Option<List<String>>> _uploadImagesToFirestorage() async {
return await productRepo
.uploadProductImages(
images: (product.value.pickedImages) as ListOf5<File>) // Exception
}
The Exception Is:
The argument type 'ListOf5 < dynamic>' can't be assigned to the
parameter type 'ListOf5 < File>'.
You are trying to cast the List from List<dynamic> to List<String>.
Instead, you should cast each item, using something like this:
void main() {
List<dynamic> a = ['qwerty'];
print(List<String>.from(a));
}
Not sure about the implementation of this ListOf5 though...
The cast (product.value.pickedImages) as ListOf5<File> fails.
It fails because product.value.pickedImages is-not-a ListOf5<File>, but instead of ListOf5<dynamic> (which may or may not currently contain only File objects, but that's not what's being checked).
Unlike a language like Java, Dart retains the type arguments at run-time(it doesn't do "erasure"), so a ListOf5<dynamic> which contains only File objects is really different from a ListOf5<File> at run-time.
You need to convert the ListOf5<dynamic> to a ListOf5<File>.
How to do that depends on the type ListOf5, which I don't know.
For a normal List, the two most common options are:
(product.value.pickedImages).cast<File>(). Wraps the existing list and checks on each read that you really do read a File. It throws if you ever read a non-File from the original list. Perfectly fine if you'll only read the list once.
List<File>.of(product.value.pickedImages). Creates a new List<File> containing the values of product.value.pickedImages, and throws if any of the values are not File objects. Requires more memory (because it copies the list), but fails early in case there is a problem, and for small lists, the overhead is unlikely to be significant. If you read the resulting list many times, it'll probably be more efficient overall.
If the ListOf5 class provides similar options, you can use those. If not, you might have to build a new ListOf5 manually, casting each element of the existing ListOf5<dynamic> yourself.
(If the ListOf5 class is your own, you can choose to add such functionality to the class).
F# has a rather nice syntax for events, which can be subscribed to as observables without any custom code for that purpose. I am creating an event that publishes updates to a member variable. I intend to subscribe to this event as an observable, but I want the existing value (which I know exists) to be pushed on subscription. Is this possible and simple to do with the event syntax, or do I need to create a proper observable using e.g. BehaviorSubject?
This depends a lot on how you plan to use it.
When you convert from an event to an observable, the EventArgs are mapped through as the observable's type. With a "standard" event, this won't have a value (EventArgs doesn't carry any information).
However, you can easily use a custom event type, or event violate normal .NET guidelines for events and use the value itself:
let evt = Event<int>()
let obs = evt.Publish :> IObservable<_>
obs |> Observable.add (fun v -> printfn "New value: %d" v)
evt.Trigger 3
evt.Trigger 4
That being said, depending on your use case, you may want to look at Gjallarhorn. This library was specifically designed for tracking changes to mutable values and signaling nicely. It's built around the concept of a "signal", which is an observable that contains a current value. This makes the above concept first class - you can pass something (a signal) that can directly be used as an IObservable whenever needed, but also can always be used to get the underlying, current value. In practice, this dramatically simplifies many use cases.
Where is it gone ?
let triggerFindNext,findNextEvent = IEvent.create<EventArgs>()
The field, constructor or member 'create' is not defined
maybe I must to add some Framework for it ?
The IEvent.create function has been deprecated. A new way of creating events is to create instance of the Event type. In the simplest case you can write just this:
let evt = new Event<EventArgs>()
// Trigger event (instead of first element of the tuple)
evt.Trigger()
// Returns IEvent<EventArgs> value (instead of second element of the tuple)
evt.Publish
This represents event using IEvent<_> value (and doesn't generate .NET compatible event if you expose it as a property) and it uses generic Handler<_> delegate from F# libraries.
(If you want to generate .NET compatible event usable from C# then you need to add CLIEvent attribute and you can use variant of Event that takes delegate as generic parameter as described in the answer already mentioned by others)
EDIT: I posted a more complete F# snippet (with nicer formatting) here: http://fssnip.net/1d
[Bindable]
/**
* Display output of video device.
*/
public var videoLocal : Video;
Anyone knows?
[Bindable] is a one of several meta tags that you can use in flex ActionScript code. It can be applied to properties, or methods that are marked in any scope. It cannot be used with static class members.
The key to using the [Bindable] meta tag is understanding what is going on under the hood when you use it. Essentially using data binding is a type of shorthand for adding event listeners and dispatching events.
There are two basic forms of the [Bindable] tag. The first is just [Bindable] followed by a var/property declaration. The Second is [Bindable(event="eventname")] followed by either a var/property declaration, a function/method declaration or one half of a getter/setter declaration.
I'll explain the longer notation first since the other builds on the same concept but with even more shorthand.
When you use [Bindable(event="eventname")] you are essentially telling the compiler that this var/property/function/method (call this the instance member) is 'available' to be used as the source for data binding. You are also telling it that when the value of the instance member has been invalidated/changed and it needs to be re-read that the "eventname" event will be dispatched.
In this longer form this all you are doing. You the developer are responsible for actually dispatching the "eventname" event whenever the value needs to be updated in the binding subscribers.
The real efficiency of using data binding comes on the subscribing side. The typical notation you will see in MXML is value="{instance.propertyName}" When you use the notation { } you are telling the compiler to do the following:
Create an event listener that listens to the event named in the bindable meta tag
In that event listener re-read the instance.propertyName and update this value
If you use the shorter form [Bindable], and you add the tag before a property/var, the compiler fills in the blanks and adds some additional functionality to make the property bindable. Essentially you are telling the compiler "add the events and methods you need to make this property bindable"
Now the way to think of what the compiler will do under the hood is this.
make a private version of your var
create an "event" to trigger the binding
create a getter function with scope and name of your original var that returns the private verson of the var when called.
create a setter function with scope and name of your original var that sets the private version of the var when called AND dispatches the triggering event.
In essence the compiler will do much of the work for you.
[Bindable]
public var xyz
is equivalent to
private var _xyz:String;
[Bindable(event="updateXYZValue")]
public function get xyz():String{
return _xyz;
}
public function set xyz(newxyz:String):void{
_xyz = newxyz;
dispatchEvent(new Event("updateXYZValue"));
}
The only functional differences in these is that in the first instance;
you do not know the name of the event that will be dispatched to trigger the binding
there is no way to update the underlying value without triggering the data binding
This second example also demonstrates one special case of the [Bindable] meta tag. This is that when you are applying it to a getter/setter pair defined for the same variable name you need only apply it to one or the other, it will apply to both. Typically you should set it on the getter.
You can use either notation on a function/method however if you do not specify an event the binding will never be triggered so if you are trying to bind to a function you should alway specify an event. It is also possible to specify more than one triggering event by stacking the tag. eg.
[Bindable(event="metaDataChanged")]
[Bindable(event="metaObjectUpdated")]
public function readMyMetaData():MetaDataObject{
var myMetaDataObject:MetaDataObject;
.
.
.
return myMetaDataObject;
}
This would presume that somewhere else you your class you will dispatch this metaDataChanged event or the metaObjectUpdated event when you want trigger the binding.
Also note that with this notation you can tie the binding of any instance member to any event that the instance will dispatch. Even inherited events that you yourself do not generate such as FrameEnter, OnChange, etc...
Data bindings can also be setup and destroyed during runtime. If you are interested in this take a look at the mx.binding.utils classes.
It is used in Databinding with Flex, you can read more about it here
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_2.html
Creating properties to use as the source for data binding
When you create a property that you
want to use as the source of a data
binding expression, Flex can
automatically copy the value of the
source property to any destination
property when the source property
changes. To signal to Flex to perform
the copy, you must use the [Bindable]
data tag to register the property with
Flex.
As an addition to what Justin said, you can actually use two ways data binding in Flex with the # character. Here's an example:
<s:TextInput id="txt1" text="#{txt2.text}" />
For a working example with source code enabled you can check out this article I wrote a while back:
Two-ways data binding in Flex
Is there a clever way to record changes made to an object in F#?
I have been researching F# as a way to build an object model that replicates itself over the network. One task I need to solve is how to detect changes made to objects so I can send only changes to clients
Note: I am looking for answers other than "implement INotifyPropertyChanged" or "do something that can easily be done in C#". If that is the only way to solve the problem in F# then F# is not the tool im looking for.
Why F#? Because I am not satisfied with the ways this state observer pattern is implemented in C#. Hence I am investigating if there is some elegant way to implement it in a dynamic language, starting with F#.
Instead of detecting and notifying changes as they happen, you could make your classes immutable (for example by using the standard immutable types like records and unions, or by making the object contain only immutable things). Then you could write a function that "diffs" two instances of a class, and have some agent that looks for changes on a schedule or based on some trigger and sends the diffs to the other end.
Because the data would be immutable, the agent would only need to retain a pointer to the version it last sent. The diffing function itself could either be written by hand for each class, which would allow for an efficient implementation that takes the properties of the data into account, or you could write a generic one using reflection.
An example of INotifyPropertyChanged use in F#.
type DemoCustomer() =
let mutable someValue = 0
let propertyChanged = Event<_, _>()
member this.MyProperty
with get() = someValue
and set(x) =
someValue <- x
propertyChanged.Trigger(this, PropertyChangedEventArgs("MyProperty"))
interface INotifyPropertyChanged with
[<CLIEvent>]
member this.PropertyChanged = propertyChanged.Publish
How about using the INotifyPropertyChanged interface? and raise events that cause the data to be replicated when it is changed?
I'd use a proxy library: Castle DynamicProxy, LinFu, Spring.NET, etc.
Using a proxy library you can easily implement INotifyPropertyChanged in a transparent, non-invasive way.
Can you use reflection to walk the object fields and see what changed? If they contain immutable F# data then equality checks will pick up the changes. You can then send the diffs relative to the last sent object.