RxJava 2: Replacement for Subject<T,R> - rx-java2

In RxJava 1.x it was possible to do a T -> R conversion in a Subject. For example the input type could be a Integer and the output type could still be a String. In RxJava 2.0 this option has been removed, now it's just Subject<T> instead of Subject<T,R>. This change is also mentioned in the What's different in 2.0 document on the RxJava wiki, but unfortunately no replacement is given. Is there any apart from declaring the Subject as Subject<Object>?

One method is to split the input and output points:
Subject<T> input = ...;
Observable<R> output = input.map(...);
Previous uses of the subject can be directed at output while the input gets redirected through input.

Related

Confused about Observable vs. Single in functions like readCharacteristic()

In the RxJava2 version of RxAndroidBle, the functions readCharacteristic() and writeCharacteristic() return Single<byte[]>.
The example code to read a characteristic is:
device.establishConnection(false).flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUUID))
But the documentation for flatMap() says the mapping function is supposed to return an ObservableSource. Here, it returns a Single. How can this work?
Update: I looked at possibilities using operators like .single() and .singleOrError() but they all seem to require that the upstream emits one item and then completes. But establishConnection() doesn't ever complete. (This is one reason I suggested that perhaps establishConnection() should be reimagined as a Maybe, and some other way be provided to disconnect rather than just unsubscribing.)
You're totally correct, this example cannot be compiled. it's probably leftover from RxJava1 version, where Single wasn't exists.
Simple fix with the same result is to use RxJava2 flatMapSingle for instance:
device.establishConnection(false)
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUUID))
flatMapSingle accepts a Single as the return value, and will map the success value of the input Single to an emission from the upstream Observable.
The point is, that RxJava has more specific Observable types, that exposes the possible series of emission expected from this Observable. Some methods now return Single as this is the logical operation of their stream (readCharacteristic()), some Observable as they will emit more than single emission (establishConnection() - connection status that can be changed over time).
But RxJava2 also provided many operators to convert between the different types and it really depends on your needs and scenario.
Thanks Rob!
In fact, the README was deprecated and required some pimping here and there. Please have a look if it's ok now.
I think I found the answer I was looking for. The crucial point:
Single.fromObservable(observableSource) doesn't do anything until it receives the second item from observableSource! Assuming that the first item it receives is a valid emission, then if the second item is:
onComplete(), it passes the first item to onSuccess();
onNext(), it signals IndexOutOfBoundsException since a Single can't emit more than one item;
onError(), it presumably forwards the error downstream.
Now, device.establishConnection() is a 1-item, non-completing Observable. The RxBleConnecton it emits is flatMapped to a Single with readCharacteristic(). But (another gotcha), flatMapSingle subscribes to these Singles and combines them into an Observable, which doesn't complete until the source establishConnection() does. But the source doesn't ever complete! Therefore the Single we're trying to create won't emit anything, since it doesn't receive that necessary second item.
The solution is to force the generation of onComplete() after the first (and only) item, which can be done with take(1). This will satisfy the Single we're creating, and cause it to emit the Characteristic value we're interested in. Hope that's clear.
The code:
Single<byte[]> readCharacteristicSingle( RxBleDevice device, UUID characteristicUUID ) {
return Single.fromObservable(
device.establishConnection( false )
.flatMapSingle( connection -> connection.readCharacteristic( characteristicUUID ) )
.take( 1L ) // make flatMapSingle's output Observable complete after the first emission
// (this makes the Single call onSuccess())
);
}

Extract Types/Classnames from flat Modelica code

I was wondering if there already exists a possibility to extract from flat Modelica code all variables AND their corresponding types (classnames respectively).
For example:
Given an extract from a flattened Modelica model:
constant Integer nSurfaces = 8;
constant Integer construction1.nLayers(min = 1.0) = 2 "Number of layers of the construction";
parameter Modelica.SIunits.Length construction1.thickness[construction1.nLayers]= {0.2, 0.1} "Thickness of each construction layer";
Here, the wanted output would be something like:
nSurfaces, Integer, constant;
construction1.nLayers, Integer, constant;
construction1.thickness[construction1.nLayers], Modelica.SIunits.Length, parameter
Ideally, for construction1.thickness there would be two lines (=number of construction1.nLayers).
I know, that it is possible to get a list of used variables from the dsin.txt, which is produced while translating a model. But until now I did not find an already existing way to get the corresponding types. And I really would like to avoid writing an own parser :-).
You could try to generate the file modelDescription.xml as defined by the FMI standard. It contains a ton of information and XML should be easier to parse, e.g. python has a couple of xml parsing/reading packages.
If you are using Dymola you just set the flag Advanced.FMI.GenerateModelDescriptionInterface2 = true to generate the model description file.
The second idea could be to let the compiler/tool parse the Modelica file for you as they need to do that anyway, try searching for AST (abstract syntax tree). In Dymola, this is available through the ModelManagement library, and also through the Python interface.
Third idea could be to use one of the Modelica parsers available, e.g. have a look at:
https://github.com/lbl-srg/modelica-json
https://hackage.haskell.org/package/modelicaparser
https://github.com/xie-dongping/modparc
https://github.com/pymoca/pymoca
https://github.com/pymola/pymola/tree/master/src/pymola
Fourth, if all that did not work, you still do not have to write a full parser, you could use ANTLR, then use an existing grammar file (look for e.g. modelica.g4).

Reactive extensions documentation

I encountered an RX method that I have not seen before and went to MSDN to take a look at any documentation that there may be.
The method was
public static IObservable<IList<TSource>> CombineLatest<TSource> (this IEnumerable<Iobservable<TSource>> sources)
I am familiar with a CombineLatest that takes an Observable as a parameter and a transform function and returns an Observable.
Unfortunately MSDN only has a page for "Observable.CombineLatest<TFirst, TSecond, TResult> Method".
Am I looking in the wrong place or am I missing a better place to see RX API documentation, other than MSDN?
The MDSN documentation is awful. The two best sites I have found are http://introtorx.com and http://reactivex.io. Neither site though has info on that overload. :)
Basically once each observable has emitted a value, then combine latest emits a new list every time one of the streams emits one. The list contents are a list of the latest values from each of the child streams. If a stream completes, that value is propagated forever. If a stream errors, the combined stream errors.
You can run the following in LinqPad to demonstrate what it does:
var letters = new Subject<string>();
var numbers = new Subject<string>();
var observables = new IObservable<string>[] { letters, numbers };
var combineLatest = observables.CombineLatest();
combineLatest.Dump("CombineLatest");
numbers.OnNext("0");
numbers.OnNext("1");
letters.OnNext("A");
letters.OnNext("B");
numbers.OnNext("2");
letters.OnNext("C");
letters.OnNext("D");
numbers.OnCompleted();
letters.OnNext("E");
letters.OnError(new Exception());
Marble diagram:
Letters: ------A--B-----C--D-----E--x
Numbers: 0--1--------2--------|
--------
Combine: ------A1-B1-B2-C2-D2----E2-x

Specification and correct use of (boolean) URI matrix parameters (and making them optional when using CXF/JAXB)?

I was wondering if the "proper" use of URI/URL matrix parameters was ever defined in a specification, such as an RFC or a W3 recommendation?
In particular, I just joined a project where we use matrix parameters and a Java framework to implement a REST service. One of the matrix parameters we have for our REST service is a boolean one, much like ;sortByDate=true
What bugged me about this one is that the Java framework we use apparently insists that boolean parameters are always passed in (i.e. you cannot make them optional/omit them; probably because they are converted to Java boolean type). I think that's a bit odd...
I have to doublecheck what framework we use tomorrow (I think it is JAXB), but in the meantime I wondered if matrix parameters were defined in an official specification somewhere, and if such a specification made any mention of boolean parameters.
So far I found a hint (though no mention of boolean matrix parameters) in Appendix B 2.2 of the W3's "HTML 4.01 Specification":
We recommend that HTTP server implementors, and in particular, CGI implementors support the use of ";" in place of "&" to save authors the trouble of escaping "&" characters in this manner.
And the "Web Application Description Language" specification specifies:
Boolean matrix parameters are represented as: ';' name when value is true and are omitted from identifier when value is false
What I haven't found is "the" specification for matrix parameters. Is there any? Does it mention how boolean matrix parameters should be used? If not, is there an established best practice?
And, as a bonus question: can you omit boolean URL matrix parameters when using CXF (JAXB), or do you always have to specify them?
Cheers! :)
Update: We're using CXF (which apparently uses JAXB under the hood...)
RFC3986 describes Matrix Parameters without explicitly naming them. Quoting https://www.rfc-editor.org/rfc/rfc3986#section-3.3:
For example, the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes. For example, one URI producer might use a segment such as "name;v=1.1" to indicate a reference to version 1.1 of "name", whereas another might use a segment such as "name,1.1" to indicate the same.
I hope this helps.
I think that this answer does a good job of explaining the purpose of matrix parameters:
https://stackoverflow.com/a/5602678
You can use the Boolean wrapper class to support an optional boolean value. The values true and false will be mapped to the correct boolean values.
#MatrixParam("sortByDate") Boolean sortByDate
It will be null if the param is not present. Note that JAXB doesn't apply when dealing with JAX-RS parameters.

In Scala, is it possible to simultaneously extend a library and have a default conversion?

For example in the following article
http://www.artima.com/weblogs/viewpost.jsp?thread=179766
Two separate examples are given:
Automatic string conversion
Addition of append method
Suppose I want to have automatic string conversion AND a new append method. Is this possible? I have been trying to do both at the same time but I get compile errors. Does that mean the two implicits are conflicting?
You can have any number of implicit conversions from a class provided that each one can be unambiguously determined depending on usage. So the array to string and array to rich-array-class-containing-append is fine since String doesn't have an append method. But you can't convert to StringBuffer which has append methods which would interfere with your rich array append.