2

I am using RXJava on Android for asynchronously access the database.

I want to save an object in my database. In this way, I created a method which take a final parameter (the object I want to save) and returns an Observable.

At this point I don't care to emit anything so I will call subscriber.onComplete() at the end.

Here is my code:

public Observable saveEventLog(@NonNull final EventLog eventLog) {
    return Observable.create(new Observable.OnSubscribe<Object>() {
        @Override
        public void call(Subscriber<? super Object> subscriber) {
            DBEventLog log = new DBEventLog(eventLog);
            log.save();
            subscriber.onCompleted();
        }
    });
}

The thing is, I saw many answer using the final keyword for the parameter, but I would like to do this without it. The reason is I don't really like the approach of declare a final variable in order to use it in another thread.

Is there any alternative? Thanks.

Daniele Vitali
  • 3,848
  • 8
  • 48
  • 71
  • 1
    Just have a varaible outside of the method initialize it in the method and use it in annonymous inner class – Raghunandan Dec 10 '15 at 12:06
  • 1
    Why would `final` be harmful? It allows the compiler to pass the value into the constructor of the anonymous inner class, much like you would do manually if you were to extract the anonymous inner class. – nhaarman Dec 10 '15 at 12:08

1 Answers1

7

We usually suggest avoiding the use of create because it may seem simple to use it but they usually violate the advanced requirements of RxJava. Instead, you should use one of the factory methods of Observable. In your case, the just factory method will get what you wanted: no final parameter:

public Observable<?> saveEventLog(@NonNull EventLog eventLog) {
    return Observable
    .just(eventLog)
    .doOnNext(e -> {
         DBEventLog log = new DBEventLog(e);
         log.save();
    })
    .ignoreElements();
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Thanks for your answer, but, following your answer, I am now wondering why creating an observable from `create` is not the best approach. I opened another thread [here](http://stackoverflow.com/questions/34204802/creating-observable-without-using-observable-create) maybe you can help me :) – Daniele Vitali Dec 10 '15 at 14:47