Assume we have an rxjava observable as a class field:
public class MyClass {
private final Observable<Integer> myObservable = Observable.just(1);
public Observable<Integer> getMyObservable() {
return myObservable;
}
}
In this case there is just one instance of the observable which is shared to class clients.
What about performance hits when returning always a new observable instance:
public class MyClass{
public Observable<Integer> getMyObservable() {
return Observable.just(1);
}
}
I'm asking because in my codebase I have a lot of those observables which are created and returned on the method call. I'm wondering if it would be a good idea just to create class instances which are then returned?
I don't think there is a big difference in terms of performance. Anyway I see a problem in the first implementation: I think that you are not going to use always 1 as item to be emitted from the Observable
. Probably, indeed, you want something like:
public class MyClass {
private int value = 100;
private final Observable<Integer> myObservable = Observable.just(value);
public Observable<Integer> getMyObservable() {
return myObservable;
}
}
I mean, I expected a parameter of the class to be emitted, like in the example.
The problem with this is that the emitted value will always be 100, regardless of the next value that the variable will assume. Let's see an example:
MyClass mc = new MyClass();
mc.getMyObservable().subscribe(value -> print(value));
mc.setValue(200);
mc.getMyObservable().subscribe(value -> print(value));
You expect 100 and 200 to be printed, but what you will get is a double 100. This is because when you assign your Observable.just(value)
to the variable myObservable
you are fixing the value that will be emitted always.
In order to prevent this you can use defer
operator:
private final Observable<Integer> myObservable = Observable.defer(() -> Observable.just(value));
So now, the emitted item from the observable will be the value of your variable at the moment of the subscription.
NOTE: You can achieve the same result using fromCallable
operator:
private final Observable<Integer> myObservable = Observable.fromCallable(() -> value);