How do I spoon feed an IObservable from procedural code? - c#-4.0

Most sample codes around Reactive Extensions revolves around how you compose logic and operators on the sequence.
The parts around Observable generation focus around "FromEventPatter","FromAsynch" etc.
IObservable<string> observableHotStatus = ??;
foreach (var task in todo)
{
//Process task;
//Post status message into observable; How do I do this?
}
In short, I want an object that I can post into, like an ActionBlock, Action (of T) or something like that.
What's the easiest way to achieve this?

Edit:
Examining your code more closely, I'd recommend using Observable.Create. Even though it only returns a cold observable, you can apply the Publish operator to the generated observable to make it hot.
And if by task you're actually referring to Task<T>, then you can use an overload of Observable.Create that allows you to define an async iterator. For example:
IObservable<string> statuses = Observable.Create<string>(
(observer, cancel) =>
{
foreach (var task in todo)
{
cancel.ThrowIfCancellationRequested();
await task;
observer.OnNext("Status");
}
});
Previous Answer:
You could use one of the following types, but I suggest reading To Use Subject or Not To Use Subject first before making your decision.
Subject<T>: General purpose, "event"-like, hot observable. Calling OnNext is like raising a classic .NET event.
BehaviorSubject<T>: Generally used as the backing field for a property, it represents an observable sequence of change "events". Whenever an observer subscribes, it receives the current value immediately, followed by all changes to the property. You can extract the current value at any time from the Value property; e.g., within your property's getter. Call OnNext within your property's setter and you don't have to keep a duplicate backing field. It's also Rx's version of a continuous function and it's the only FRP-like thing you'll find in Rx, if my understanding of FRP is correct.
ReplaySubject<T>: Generally used as an historical buffer of "events", it represents an observable sequence of values beginning with the values that have been missed by an observer, whenever an observer subscribes. You can control how far back values are buffered; it's like a sliding window over the history of values. You rarely have to use this type. In most cases, the Observable.Replay operator will do.
AsyncSubject<T>: Generally used to capture the results of hot, asynchronous functions like Task<T>. You rarely have to use this type. In most cases, Observable.FromAsyncPattern or Task-conversion operators will do.

Related

Difference between different "resolve" functions in a custom NSMergePolicy

When implementing a custom NSMergePolicy, there are 3 functions available to overload:
final class MyMergePolicy: NSMergePolicy {
override func resolve(mergeConflicts list: [Any]) throws {
// ...
try super.resolve(mergeConflicts: list)
}
override func resolve(optimisticLockingConflicts list: [NSMergeConflict]) throws {
// ...
try super.resolve(optimisticLockingConflicts: list)
}
override func resolve(constraintConflicts list: [NSConstraintConflict]) throws {
// ...
try super.resolve(constraintConflicts: list)
}
}
Documentation for all 3 is exactly the same, it says: "Resolves the conflicts in a given list.", and I can't seem to find much information online.
What's the difference between these functions? What are the appropriate use cases for each of them?
The documentation kind of sucks here but you can get a partial explanation by looking at the arguments the functions receive.
resolve(optimisticLockingConflicts list: [NSMergeConflict]): Gets a list of one or more NSMergeConflict. This is what you'll usually hear about as a merge conflict, when the same underlying instance is modified on more than one managed object context.
resolve(constraintConflicts list: [NSConstraintConflict]): Gets a list of one or more NSConstraintConflict. This happens if you have uniqueness constraints on an entity but you try to insert an instance with a duplicate value.
The odd one out is resolve(mergeConflicts list: [Any]). This one is basically a leftover from the days before uniqueness constraints existed. It gets called for both types of conflict described above-- but only if you don't implement the more-specific function. So for example if you have a constraint conflict, resolve(constraintConflicts:...) gets called if you implemented it. If you didn't implement it, the context tries to fall back on resolve(mergeConflicts list: [Any]) instead. The same process applies for merge conflicts-- the context uses one function if it exists, and can fall back on the other. Don't implement this function, use one of the other two.
For both conflict types, the arguments give you details on the conflict, including the objects with the conflict and the details of the conflict. You can resolve them however you like.

LitElement and .bind(this)

I'm finding a little confusing sometimes you need to bind the context to a function call and sometimes not. When exactly can you avoid it and when you not?
What's the difference between those lines?
<a #click="${this.handler.bind(this)}">link</a>
<a #click="${this.handler()}">link</a>
<a #click="${this.handler}">link</a>
<a #click="${()=>this.handler()}">link</a>
Also sometimes in the constructor() you need
this.handler = this.handler.bind(this)
to make the function call works, sometimes you not. What's the differences between all those cases?
In the first 4 lines I am guessing you usually wrap them in between ${ and }.
With this mention these 3 lines:
<a #click="${this.handler.bind(this)}">link</a>
<a #click="${this.handler}">link</a>
<a #click="${()=>this.handler()}">link</a>
would be pretty similar in the effect. When you attach an event handler you need to pass a reference to a function/method to call, while the second line:
<a #click="${this.handler()}">link</a>
will most likely just be wrong. That's because you will be calling this.handler() as soon as the rendering is done. The only way it might make some sense it would be if the handler method returns a function.
Going back to the first 3 lines: they will indeed have very similar effect, as in all of them you are passing references to a local method render, but:
the first one doesn't need binding as the method will anyway be
called in this context (but I guess it doesn't hurt either)
the third one adds the definition of an anonymous function as an
event handler, which when called it will invoke this.handler
So the second one is basically the simplest and easiest to read.
When it comes to the need to call bind in some of the cases: that's needed when your method is called from another context. Let's say you pass it as a callback parameter to a method running in another class. When you method will be called there, it will have by default the context of that other object. So you will need to use .bind(this) to make sure that when the method is called in your element's context.
Your method does work, but it's running from another this. So maybe that's why some of the times you don't notice the need to .bind(this). If the method just shows a message, calls some other external service, or anything else that is not part of your object's definition (that doesn't use this.something), it will work without using bind.
UPDATE: in fact I think an event handler will always run in the context of the element that originated that event. I am guessing that lit just does that .bind(this) when we use that #click= syntax, as it would make a lot of sense.
Note that binding directly in templates is generally not a good idea. It can result in performance issues and components re-rendering when they shouldn't.
https://github.com/43081j/eslint-plugin-lit/blob/master/docs/rules/no-template-bind.md
As to why you sometimes need to bind consider this:
#customElement('main-page')
export class MainPage extends LitElement {
#property()
public name = "bob";
render() {
return html`<button #click=${this.clicked}>Click Me!</button>`;
}
clicked() {
console.log("clicked " + this.name);
console.log("this in clicked: " + this)
setTimeout(this.sayHi, 1000);
}
sayHi() {
console.log("this in sayHi: " + this)
alert(`Hello, ${this.name}!`);
}
}
If we click on the button, we get the name logged properly:
But the name isn't shown in the alert:
If we look at this in both functions we get different results:
One is an HTMLElement and the other one is a Window. What this refers to is different once we pass sayHi to setTimeout.
Bind will fix this by making sure that this refers to the right object.
While we could do setTimeout(this.sayHi.bind(this), 1000); and it would fix our issue but it's not very clean and it's error prone. We could bind it in the constructor, but this also isn't much better.
The cleanest way to do it is to directly bind this by using an arrow function instead:
sayHi = () => {
[...]
This notation binds this to the object itself. We then do not need to bind it explicitly ourselves.
Once we do that, both this refer to the right object:

Best practices for callbacks within a scope

Typically, in "constructor" you subscribe to events with lambda-functions:
function Something(){
this.on('message', function(){ ... });
}
util.inherits(Something, events.EventEmitter);
This works well but extends bad. Methods play better with inheritance:
function Something(){
this.on('message', this._onMessage);
}
util.inherits(Something, events.EventEmitter);
Something.prototype._onMessage = function(){ ... };
What are the best practices to keep these event handler functions?
if i understood the question correctly then i think that it depends on how much open for changes you are willing to be.
your second example opens the option for subclasses (or, actually, any class) to override the handler's code, which isn't necessarily a good thing.
the first example prevents overriding but at the cost of having anonymous functions (sometimes containing a lot of code) inside your constructor. however, this code can be extracted to another private function (not on the prototype, just a regular function inside the module's file).
the open-close principal deals with this kind of questions.

Separating Logic/GUI and user interaction

imagine you have a function that creates/copies/moves files. [logic]
For the case that a file that should be copied/created already exists you would like to ask the user to overwrite the file or not.[(G)UI]
What is your approach to implement this if (G)UI and logic are completely separated?
The first thing that comes into my mind would be the MVC-pattern, but this means that I would have to use it whereever I need user interaction.
Any other suggestions?
BTW: How would you implement this in non-OO-languages?
If GUI and logic are really separated, then this question should never arise. The program should, by design, either overwrite or not overwrite based on an option which has a default value. If the GUI is available, the option can be set.
In fact, although the obvious approach is to just have at it and begin copying, you could make a first pass looking for conflicts, and checking that the target device has enough free storage. Then, if there is a problem, terminate by doing nothing, unless there is a GUI in which case you can report the problem and ask whether to proceed anyway.
If you want to have a design in which the GUI can be invoked on a file by file basis, then design the logic around that as a set of n processes each of which copies one file, and has an optional GUI available in the error reporting section. The GUI can then reinvoke the copy-one-file logic.
I can see two ways:
You have two functions, file_exists(...) and copy_file(...). The UI side always calls file_exists first and asks the user whether to copy the file is it already exists.
You have only one function copy_file(bool force, ...), that by default fails if the file exists. So UI side calls the default version of the function, check if it failed and why, if it was because the file already exists, ask the user and try again with force=true.
In a Non OO language I would implement some kind of event queue where the parent (or child, depending on your design) UI polled for events while a 'busy' flag was true. Such an event lets the other side do other work while waiting for a 'they answered' flag to come true. Of course, some timeout in both directions would have to be observed as well as mutual exclusion. Basically, imply the principles of non-blocking I/O or your favorite theory on practical lock free programming here.
There are degrees of separation .. processes can communicate. Depending on your language of choice, you have shared memory segments, semaphores .. or IPC via relational DB with primitive signals. Its hard to be more specific with such a generic question.
See my comment, a little more information is needed so an answer can be crafted that works within your language of choice.
The first thing that comes into my mind would be the MVC-pattern, but this means that I would have to use it wherever I need user interaction.
And this is a bad thing why? Separating GUI and logic is exactly what the MVC pattern is for. Don't be scared of it just because it a has a long name -- as soon as you've separated GUI and logic you have a "view" and a "controller", at least, if not a "model" -- and if your application has state, you've got a model too. You just may not have admitted it to yourself yet.
From what I can see, there are really two problems:
We have an algorithm (logic) in which we would like to defer some operations and decisions to something else (e.g. user via UI).
We would like to avoid tight coupling between the algorithm and that something else.
If we use OO languages, there are several design patters which address these two specific problems.
Template Method pattern can solve #1. It does not solve #2 very well because the typical implementation is via inheritence.
Observer pattern looks promising too.
So really it is choosing and mixing the simplest one for the needs and most suitable for the language.
In practical terms, if talk about C# for example, we can implement Template Method and Observer hybrid like this:
// This will handle extensions to the FileCopy algorithm
abstract class FileCopyExtention
{
public abstract Response WhatToDoWhenFileExists();
}
// the copy function, pure logic
public static void Copy(string source, string destination, FileCopyExtention extension)
{
if (File.Exists(destination))
{
var response = _extension.WhatToDoWhenFileExists();
if (response == overwrite)
// overwrite the file
else
// error
}
}
// This is our user-interactive UI extension
class FileCopyUI : FileCopyExtention
{
public override Response WhatToDoWhenFileExists()
{
// show some UI, return user's response to the caller
}
}
// the program itself
void Main()
{
Copy("/tmp/foo", "/tmp/bar", new FileCopyUI());
}
As a variation of the theme, you can use events, delegates or whatever the language of your choice provides.
In C, this could be a function pointer, in C++ a reference to a class I guess.
What about this approach [pseudo-code]:
UIClass
{
//
// Some code
//
bool fileCopied = false;
do {
try {
fileCopied = CopyFile(fileName);
} catch (FileExists) {
//
// Ask "File exists! Overwrite?" If "No", exit do-loop
//
} catch (FileLocked) {
//
// Ask "File Locked! Repeat?", If "No", exit do-loop
//
} catch (etc...) {
//
// etc.
//
}
} while (!fileCopied);
//
// Some code
//
}
LogicClass
{
//
// Some code
//
bool CopyFile(string fileName)
{
//
// copy file
//
}
//
// Some code
//
}

IDynamicObject implementation ignores multiple property invocations

I've implemented IDynamicObject in C# 4, return a custom MetaObject subclass that does simple property getter/setter dispatch to a Dictionary. Not rocket science.
If I do this:
dynamic foo = new DynamicFoo();
foo.Name = "Joe";
foo.Name = "Fred";
Console.WriteLine(foo.Name);
Then 'Joe' is printed to the console... the second call to the 'Name' setter is never invoked (never steps into my custom dispatcher code at all).
I know the DLR does callsite caching, but I assumed that wouldn't apply here. Anyone know what's going on?
Whatever MetaObject you're returning from (Bind)SetMember will be cached and re-used in this case. You have 2 dynamic sites doing sets. The 1st call will cache the result in an L2 cache which the 2nd site will pick up before asking you to produce a new rule.
So whatever MetaObject you're returning needs to include an expression tree that will update the value. For example it should do something like:
return new MetaObject(
Expression.AssignProperty(this.Expression, value.Expression),
Restrictions.TypeRestriction(this.Expression, this.Value.GetType());

Resources