将参数传递给 Observable.create [英] Passing parameter to Observable.create

查看:36
本文介绍了将参数传递给 Observable.create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 上使用 RXJava 来异步访问数据库.

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

我想在我的数据库中保存一个对象.通过这种方式,我创建了一个方法,它接受一个最终参数(我想保存的对象)并返回一个 Observable.

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.

此时我不想发出任何东西,所以我会在最后调用 subscriber.onComplete().

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

这是我的代码:

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

问题是,我看到很多答案使用 final 关键字作为参数,但我想在没有它的情况下这样做.原因是我真的不喜欢为了在另一个线程中使用它而声明一个 final 变量的方法.

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.

推荐答案

我们通常建议避免使用 create ,因为它看起来使用起来很简单,但它们通常违反了 RxJava 的高级要求.相反,您应该使用 Observable 的工厂方法之一.在您的情况下, just 工厂方法将获得您想要的:没有最终参数:

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

这篇关于将参数传递给 Observable.create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆