Passing parameter to Observable.create

蹲街弑〆低调 提交于 2020-01-06 04:22:06

问题


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:


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();
}


来源:https://stackoverflow.com/questions/34201353/passing-parameter-to-observable-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!