This is a continuation of my earlier problem. My question there is solved but I think to further ask about the code, it's better for me to open another question, since I also need to ask some other thing about it. So here's my observable
public static <T> Observable<T> makeObservable(final Callable<T> func) {
return Observable.create(
new Observable.OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
try {
T observed = func.call();
if (observed != null) { // to make defaultIfEmpty work
subscriber.onNext(observed);
}
subscriber.onCompleted();
} catch (Exception ex) {
subscriber.onError(ex);
}
}
}).map(new Func1<T, T>() {
@Override
public T call(T t) {
return null;
}
});
I don't know what is that T doing there? I tried to googled but I can't understand its role in the code above. Official java doc says its a 'A generic type is a generic class or interface that is parameterized over types'. Tried to search further about it and I came upon this question that confuses me even more.
Apart from the need to really understand the T there, I need to know how to use .map to transform the content of T. From the code above, this segment
.map(new Func1<T, T>() {
@Override
public T call(T t) {
return null;
}
is the one I add because I want to try changing the contents of T into something else, perhaps into another object. How do I achieve that? Before that, this is my understanding of the .map function in RxJava.
According to the official documentation at http://reactivex.io/RxJava/javadoc/rx/Observable.html#map(rx.functions.Func1) it says,
public final <R> Observable<R> map(Func1<? super T,? extends R> func)
Returns an Observable that applies a specified function to each item emitted by the source Observable and emits the results of these function applications.
func - a function to apply to each item emitted by the Observable
Am I correct to interpret from the definition of func above, the first parameter (super T), should be the 'incoming' data type, and the second parameter (extends R) is the 'outgoing' data type, or the data type of the transformed item. Because that's what I see from most of the code examples. Eg, from http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
Observable.just("Hello, world!")
.map(new Func1<String, Integer>() {
@Override
public Integer call(String s) {
return s.hashCode();
}
})
My understanding from the code above is Func1 receives string and passes it to call(String s), and returns Integer, as defined in Func1<String, Integer>
. So is my interpretation above will always be correct? Because from my first code, I need to change T into something else, but when I changed the 2nd parameter of .map new Func1 to anything else other than T, Android Studio will give me the "Incompatible types" error.