如何解析RxJava只接收我想要的数据?

时间:2017-04-06 12:36:55

标签: java android rx-java rx-android

我只想要数字,但这是我在日志中收到的信息:

  

[Boletim(等级= 4.5),Boletim(等级= 9.5)]

响应:

public class GradeResponse {

    @Inject
    Retrofit retrofit;

    @Inject
    MainPresenter mainPresenter;

    public void getGradeRx() {

        MyApplication.getMainComponent().injectIntoGradeResponse(this);// informando ao dagger sobre o uso de um component e a necessidade de injetar dependência

        Subscription getGrade = retrofit
                .create(GradeService.class)
                .getGrade()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(model -> {

                    return model.getBoletim();

                })
                .subscribe(new Observer<Boletim[]>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "saporra vai me matar ainda");
                    }

                    @Override
                    public void onNext(Boletim[] grades) {
                        Log.i(TAG, Arrays.asList(grades).toString());
                    }
                });
    }
}

模特:

GradeModel:

@SerializedName("boletim")
    @Expose
    private Boletim[] boletim;

Boletim.class

public class Boletim {

    @SerializedName("grade")
    @Expose
    private double grade;

改装服务没问题,依赖注入工作正常。我正在从rxJava接收onSuccess方法,我现在只需要接收没有的数字“[Boletim(grade =”

1 个答案:

答案 0 :(得分:1)

您正在看到对象的toString,因为您在地图中获得了整个对象!

  

只有没有这个数字的数字“[Boletim(grade =”。

方法你不能再次映射并提取它吗?

.map(model -> {               // This map returns a Boletim[]
     return model.getBoletim();
 })
.map(boletim -> {             // This map returns a double[]
    Double grades = new Double[boletim.length];
    for (int i =0; i < grades.length ; i++) {
        grades[i] = boletim[i].getGrade() ;
    } 
    return grades;
}).subscribe(new Observer<Double[]>() {   // This subscribes to a double[]
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        Log.i(TAG, "saporra vai me matar ainda");
    }

    @Override
    public void onNext(Double[] grades) {
        Log.i(TAG, Arrays.toString(grades));
    }
}

或者您可以将for循环放入onNext

如果您不想要Observable数组,请使用flatMap