如何应用RxJava运算符?

时间:2015-07-10 21:44:40

标签: android retrofit rx-java

我有以下对象结构

class Object1 {
  A[] item1;    //array of Object A
  B[] item2;    //array of Object B
  C[] item3;    //array of Object C
}

class C {
  int value1;
  int value2;
  String imageUrl; //null, to be updated from a api call
}

我得到Observable<Object>进行改装api通话。对象imageUrl的{​​{1}}字段为C,我必须通过进行另一次改装api调用来更新。我想使用RxJava为nullObject中的每个C C[]更新imageUrl。我怎么能用RxJava运算符呢?

我希望该方法返回更新后的Observable<Object1>

2 个答案:

答案 0 :(得分:1)

这应该有效:

String id = getResources().getString(R.string.sc_client_id);
String secret = getResources().getString(R.string.sc_client_secret);
ApiWrapper wrapper = new ApiWrapper(id,secret, null, null);

try {
    //Only needed for user-specific actions;
    //wrapper.login("<user>", "<pass>");
    //HttpResponse resp = wrapper.get(Request.to("/me"));
    //Get a track
    HttpResponse trackResp = wrapper.get(Request.to("/tracks/60913196"));
    //Track JSON response OK?
    if(trackResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
    {
        JSONObject trackJSON = new JSONObject(EntityUtils.toString(trackResp.getEntity()));
        //If track is streamable, fetch the stream URL (mp3-https) and start the MediaPlayer
        if(trackJSON.getBoolean("streamable"))
        {
            HttpResponse streamResp = wrapper.get(Request.to("/tracks/60913196/stream"));
            JSONObject streamJSON = new JSONObject(EntityUtils.toString(streamResp.getEntity()));
            String streamurl = streamJSON.getString("location");
            Log.i("SoundCloud", trackJSON.getString("streamable"));
            Log.i("SoundCloud", streamurl);
            m_soundcloudPlayer.stop();
            m_soundcloudPlayer = new MediaPlayer();
            m_soundcloudPlayer.setDataSource(streamurl);
            m_soundcloudPlayer.prepare();
            m_soundcloudPlayer.start();
        }

    }
}
catch (IOException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}catch (ParseException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}
catch (JSONException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

出于测试目的,我的getObject1() .flatMap(obj1 -> Observable.from(obj1.item3) .cast(C.class) .flatMap(item -> getImageUrl(item.value1).doOnNext(url -> item.imageUrl = url)) .toList() .map(items -> obj1)) 看起来像这样:

getImageUrl

它看起来像这样:

Observable<String> getImageUrl(int id) {
    return Observable.just(String.format("id = %d", id));
}

答案 1 :(得分:0)

我不是RxJava的专家,但是如下:

observable
    .flatMap(Observable.from(object1.item3))
    .flatMap(//do request and mix object)
    .collect()
    .filter(//map the new array to he object1)