rxjava 2.0 what is the difference between Observable.subscribe and Observable.subscribeActual? - rx-java2

The documentation just says
protected abstract void subscribeActual(Observer<? super T> observer)
Operator implementations (both source and intermediate) should implement this method that performs the necessary business logic.
There is no need to call any of the plugin hooks on the current Observable instance or the Subscriber.

Observable.subscribe comes from the base interface definition in ObservableSource and is the main subscription method for Observables: internal and external components use it to run a flow in a standard way.
However, certain actions may be necessary for all kinds of Observables to be executed before the operator's business logic gains access to the incoming Observer, for example, applying plugin hooks and protecting against crashing subscribe implementations. So instead of requiring every operator to duplicate this preparation logic, they are in a single place and a new abstract method is present to deal with the customization of an Observable.

Related

Scala: Making singleton to process a client request

Is it a good practice to make use of singleton object to process client requests?
As object instance is singleton, and if its in middle of processing a client request , and meanwhile another request arrives then same instance is invoked with new client data. Won't it make things messy?
When using singleton objects we must ensure everything inside it as well as everything it calls must be thread-safe. For example, javax.crypto.Cipher does not seem to be thread-safe, so it should probably not be called from a singleton. Consider how guice uses #Singleton to specify threadsafety intention:
#Singleton
public class InMemoryTransactionLog implements TransactionLog {
/* everything here should be threadsafe! */
}
Also consider the example of Play Framework which starting version 2.4 began moving away from singleton controllers and started encouraging class controllers.
It depends on whether the object holds any mutable data or not.
If the object is just a holder for pure functions and immutable state, it does not matter how many threads are using it at the same time because they can't affect each other via shared state.
If the object has mutable state then things can definitely go wrong if you access it from multiple threads without some kind of locking, either inside the object or externally.
So it is good practice as long as there is no mutable state. It is a good way of collecting related methods under the same namespace, or for creating a global function (by defining an apply method).

Purpose of RxJavaPlugins.onSubscribe method

Can you explain purpose of RxJavaPlugins.onSubscribe method in subscribe method of Observable class? Inputs are Observable and Observer and result is Observer.
It allows wrapping the downstream Observer into a custom Observer, allows considering the upstream source's type for the wrapping and at the end, return the wrapper Observer to be subscribed to the upstream.
You can shim behavior after specific operators this way for diagnostic purposes.

Where to register observers when using IoC containers?

In my current application, I am using a 'selfmade' Observable class in order to implement the observer pattern. Observers (implementing an interface) can listen to certain events.
I am switching more and more of the project over to using an IoC container, but I fail to find a good place in the code to register the observers with the observable.
The ways to do this that I see are:
A) Inject the observable into the observer.
The constructor shouldn't do actual work, but even with method- or field injection this couples the observer with the observable. This is also the case if it's the other way around.
B) Create an observable factory and do it there.
In this case creating the observable depends on the implementations of several observers.
C) Create the observers by factory and do it there.
While this seems best to me concerning coupling, it turns out bad concerning DRY. In some cases the factory ends up being a copy of the fields and constructor of the observer, plus the observable and plus the one line of code for the registering.
Is there a way to handle this registering in a clean way? If not, are there compelling arguments to use a certain way over the others?
The solution was discovering the difference between Resolve() and Instantiate() methods.
I was always using Resolve(). With that, I would receive an Observer in the way it has been bound to the container.
However, Instantiate() does not care about how the class is bound to the container. It creates the class the standard way, but still injects the dependencies. So this can be used inside the factory for the observer.

Preconditions and postconditions in interfaces and abstract methods

I'm trying to implement my own programming language, and i'm currently doing lexing and parsing. I'm nearly done and want to add native support for class invariants, preconditions and postconditions.
public withdraw (d64 amount) : this {
require amount > 0;
require this.balance - amount > this.overdraft;
# method code
d64 newBalance = this.balance - amount;
ensure this.balance == newBalance;
}
You would also be able to define class invariance at the top of the class.
class BankAccount {
invariant this.balance > this.overdraft;
# class body
}
These are my questions:
Would it make sense to include class invariance in abstract classes, or interfaces.
Would it make sense to include preconditions in abstract methods and interface methods.
Would it make sense to include postconditions in abstract methods, or interface methods.
Thinking about it myself, i don't think it makes sense to include invariance or postconditions in interfaces, but i don't really see a problem with preconditions.
It would be possible to include pre- and postconditions in abstract and interface methods like below.
public interface BankAccount {
public withdraw (d64 amount) : this {
require amount > 0;
require this.balance - amount > this.overdraft;
# no other statements (implementation)
d64 newBalance = this.balance - amount;
ensure this.balance == newBalance;
}
}
It really depends on whether your interface is stateful or stateless. It can be perfectly fine to include pre and/or post conditions for interface methods. In fact, we do this all the time. Any time you create a piece of javadoc (or any other tool), you are creating a contract. Otherwise, how could you test anything? It's important to realize that test-driven-development and design-by-contract have much in common. Defining a contract is essential to proper tdd - you first design an interface and create an informal contract for it (using human-readable language). Then, you write a test to ensure contract is satisfied. If we follow tdd classicists (https://www.thoughtworks.com/insights/blog/mockists-are-dead-long-live-classicists), we always write tests against contracts.
Now, to be more specific. If interface is stateful, we can easily express its invariants according to other methods. Let's take a java List interface as an example:
If you read the javadoc carefully, you will see there are a lot of invariants. For instance, the add method has the following contract:
Preconditions: element cannot be null (if list doesn't support it -
it's a design smell btw in my opinion, but let's set it aside for
now)
Postconditions: ordering is preserved, i.e. the ordering of other
elements cannot be changed
Since List interface is definitely stateful, we can reason about the state of the list using query method, like get, sublist etc. Therefore, you can express all the invariants based on interface's methods.
In case of an interface which is stateless, such as Calculator, we also define a contract, but its invariants do not include any state. So, for example, the sum method can have the following contract:
int sum(int a, int b)
Preconditions: a and b are integers (which is automatically guaranteed by static type checking in Java)
Postconditions: the result is an integer (again - type safety) which is equal to a + b
Our Calculator is a stateless interface, therefore we don't include any state in our invariants.
Now, let's get back to your BankAccount example:
The way you describe it, BankAccount is definitely a stateful interface. In fact, it's a model example of what we call an Entity (in terms of domain-driven-design). Therefore, BankAccount has it's lifecycle, it's state and can (and will) change during its lifetime. Therefore, it's perfectly fine to express your contracts based on the state methods of your class. All you need to do, is to move your amount, balance and overdraft to the top of the interface, either as properties (if your language supports it) or methods - it doesn't really matter. What's important is that amount, balance and overdraft are now part of your interface, and form the ubiquitous language of your interface. These methods/properties are integral part of your entire BankAccount interface - which means, they can be used as part of your interface's contract.
Some time ago I've implemented a very simple prototype of Java contracts, implemented as set of annotations supported by Aspect Oriented Programming. I tried to achieve similar goal to yours - to integrate contracts with language and make them more formal. It was just a very simple prototype, but I think it expressed the idea quite well. If you are interested - I should probably upload it to the github soon (I've been using bitbucket for most of the time so far).

ServiceContainer, IoC, and disposable objects

I have a question, and I'm going to tag this subjective since that's what I think it evolves into, more of a discussion. I'm hoping for some good ideas or some thought-provokers. I apologize for the long-winded question but you need to know the context.
The question is basically:
How do you deal with concrete types in relation to IoC containers? Specifically, who is responsible for disposing them, if they require disposal, and how does that knowledge get propagated out to the calling code?
Do you require them to be IDisposable? If not, is that code future-proof, or is the rule that you cannot use disposable objects? If you enforce IDisposable-requirements on interfaces and concrete types to be future-proof, whose responsibility is objects injected as part of constructor calls?
Edit: I accepted the answer by #Chris Ballard since it's the closest one to the approach we ended up with.
Basically, we always return a type that looks like this:
public interface IService<T> : IDisposable
where T: class
{
T Instance { get; }
Boolean Success { get; }
String FailureMessage { get; } // in case Success=false
}
We then return an object implementing this interface back from both .Resolve and .TryResolve, so that what we get in the calling code is always the same type.
Now, the object implementing this interface, IService<T> is IDisposable, and should always be disposed of. It's not up to the programmer that resolves a service to decide whether the IService<T> object should be disposed or not.
However, and this is the crucial part, whether the service instance should be disposed or not, that knowledge is baked into the object implementing IService<T>, so if it's a factory-scoped service (ie. each call to Resolve ends up with a new service instance), then the service instance will be disposed when the IService<T> object is disposed.
This also made it possible to support other special scopes, like pooling. We can now say that we want minimum 2 service instances, maximum 15, and typically 5, which means that each call to .Resolve will either retrieve a service instance from a pool of available objects, or construct a new one. And then, when the IService<T> object that holds the pooled service is disposed of, the service instance is released back into its pool.
Sure, this made all code look like this:
using (var service = ServiceContainer.Global.Resolve<ISomeService>())
{
service.Instance.DoSomething();
}
but it's a clean approach, and it has the same syntax regardless of the type of service or concrete object in use, so we chose that as an acceptable solution.
Original question follows, for posterity
Long-winded question comes here:
We have a IoC container that we use, and recently we discovered what amounts to a problem.
In non-IoC code, when we wanted to use, say, a file, we used a class like this:
using (Stream stream = new FileStream(...))
{
...
}
There was no question as to whether this class was something that held a limited resource or not, since we knew that files had to be closed, and the class itself implemented IDisposable. The rule is simply that every class we construct an object of, that implements IDisposable, has to be disposed of. No questions asked. It's not up to the user of this class to decide if calling Dispose is optional or not.
Ok, so on to the first step towards the IoC container. Let's assume we don't want the code to talk directly to the file, but instead go through one layer of indirection. Let's call this class a BinaryDataProvider for this example. Internally, the class is using a stream, which is still a disposable object, so the above code would be changed to:
using (BinaryDataProvider provider = new BinaryDataProvider(...))
{
...
}
This doesn't change much. The knowledge that the class implements IDisposable is still here, no questions asked, we need to call Dispose.
But, let's assume that we have classes that provide data that right now doesn't use any such limited resources.
The above code could then be written as:
BinaryDataProvider provider = new BinaryDataProvider();
...
OK, so far so good, but here comes the meat of the question. Let's assume we want to use an IoC container to inject this provider instead of depending on a specific concrete type.
The code would then be:
IBinaryDataProvider provider =
ServiceContainer.Global.Resolve<IBinaryDataProvider>();
...
Note that I assume there is an independent interface available that we can access the object through.
With the above change, what if we later on want to use an object that really should be disposed of? None of the existing code that resolves that interface is written to dispose of the object, so what now?
The way we see it, we have to pick one solution:
Implement runtime checking that checks that if a concrete type that is being registered implements IDisposable, require that the interface it is exposed through also implements IDisposable. This is not a good solution
Enfore a constraint on the interfaces being used, they must always inherit from IDisposable, in order to be future-proof
Enforce runtime that no concrete types can be IDisposable, since this is specifically not handled by the code using the IoC container
Just leave it up to the programmer to check if the object implements IDisposable and "do the right thing"?
Are there others?
Also, what about injecting objects in constructors? Our container, and some of the other containers we've looked into, is capable of injecting a fresh object into a parameter to a constructor of a concrete type. For instance, if our BinaryDataProvider need an object that implements the ILogging interface, if we enforce IDispose-"ability" on these objects, whose responsibility is it to dispose of the logging object?
What do you think? I want opinions, good and bad.
One option might be to go with a factory pattern, so that the objects created directly by the IoC container never need to be disposed themselves, eg
IBinaryDataProviderFactory factory =
ServiceContainer.Global.Resolve<IBinaryDataProviderFactory>();
using(IBinaryDataProvider provider = factory.CreateProvider())
{
...
}
Downside is added complexity, but it does mean that the container never creates anything which the developer is supposed to dispose of - it is always explicit code which does this.
If you really want to make it obvious, the factory method could be named something like CreateDisposableProvider().
(Disclaimer: I'm answering this based on java stuff. Although I program C# I haven't proxied anything in C# but I know it's possible. Sorry about the java terminology)
You could let the IoC framework inspect the object being constructed to see if it supports
IDisposable. If not, you could use a dynamic proxy to wrap the actual object that the IoC framework provides to the client code. This dynamic proxy could implement IDisposable, so that you'd always deliver a IDisposable to the client. As long as you're working with interfaces that should be fairly simple ?
Then you'd just have the problem of communicating to the developer when the object is an IDisposable. I'm not really sure how this'd be done in a nice manner.
You actually came up with a very dirty solution: your IService contract violates the SRP, wich is a big no-no.
What I recommend is to distinguish so-called "singleton" services from so-called "prototype" services. Lifetime of "singleton" ones is managed by the container, which may query at runtime whether a particular instance implements IDisposable and invoke Dispose() on shutdown if so.
Managing prototypes, on the other hand, is totally the responsibility of the calling code.