使用RxJava返回整数-subscriptionOn问题

时间:2019-07-13 20:40:47

标签: android mvvm rx-java android-livedata

@NonNull
private final NoteDao noteDao;

@Inject
public NoteRepository(@NonNull NoteDao noteDao) {
    this.noteDao = noteDao;
}

尝试完成此方法,该方法将从Sqlite数据库中返回一个int PK。

    private void insert(Note note) {

    Log.d(TAG, "saveNote: called.");
    try {
        noteDao.insert(note)
                . map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        long l = aLong;
                        return (int)l;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((new io.reactivex.functions.Consumer<Integer>() {
                    @Override
                    public void accept(Integer integerResource) {
                        // work with integerResource
                        sqCbtId = integerResource;
                    }
                })); new io.reactivex.functions.Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable error) {
                        // report the error
                    }
                };
    } catch (Exception e) {
        e.printStackTrace();
    }

*:java.lang.InstantiationException:java.lang.Class没有零参数构造函数*

1 个答案:

答案 0 :(得分:0)

尝试一下:

private void insert(Note note) {

    Log.d(TAG, "saveNote: called.");

    noteDao.insert(note)
            .map(new Function<Long, Integer>() {
                @Override
                public Integer apply(Long aLong) throws Exception {
                    long l = aLong;
                    return (int)l;
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new io.reactivex.functions.Consumer<Integer>() {
                @Override
                public void accept(Integer integerResource) {
                    // work with integerResource
                }
            }, new io.reactivex.functions.Consumer<Throwable>() {
                @Override
                public void accept(Throwable error) {
                    // report the error
                }
            });
}