Passing parameter to Observable.create

2019-08-12 15:38发布

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.

1条回答
三岁会撩人
2楼-- · 2019-08-12 16:14

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();
}
查看更多
登录 后发表回答