2017-02-14 10 views
-1

私は現在、RxJava/RxAndroidの基本を学んでおり、非常に基本的なRetrofitテストアプリケーションを作成しようとしています。RxJavaのObservable内のリストをどのように反復処理しますか?

この例ではRxJava 1.2.6を使用しています。

しかし、 Observableオブジェクト内のリストのオブジェクトに対してどのように関数を実行するかの明確な例は見つかりませんでした。

など。 (例えば、リスト内の各AgencygetName()を印刷)機能をマッピングすることが可能であるどのように私は、次のPOJOを持っている場合

public class AgencyResponse { 

    private List<Agency> agencies; 
    private int total; 
    private int count; 
    private int offset; 

    public List<Agency> getAgencies() { 
     return agencies; 
    } 

    public int getTotal() { 
     return total; 
    } 

    public int getCount() { 
     return count; 
    } 

    public int getOffset() { 
     return offset; 
    } 
} 

と同様に

public class Agency { 

    private int id; 
    private String name; 
    private String abbrev; 

    public int getId() { 
     return id; 
    } 

    public String getName() { 
     return name; 
    } 

    public String getAbbrev() { 
     return abbrev; 
    } 
} 

ときObservableオブジェクトはリストを含むクラスです。私。 Observable<AgencyResponse>

現実の世界とそのうまくいけば、より明確な例は以下の通りです:

public class MainActivity extends BaseActivity { 

private TextView textView; // Code to populate this omitted 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Create Retrofit service 
    LaunchLibService service = ServiceFactory.createRetrofitService(LaunchLibService.class, LaunchLibService.SERVICE_ENDPOINT); 

    //getAgencyList returns Observable<AgencyResponse> 
    service.getAgencyList() 
    .subscribeOn(Schedulers.newThread()) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .map(AgencyResponse::getAgencies) // Gets the List<Agency> but how do I iterate over each object and print? 
    .subscribe(); 
} 
} 

すべてのヘルプは素晴らしいことだ、ありがとうございました。

+1

はhttp://stackoverflow.com/a/42215321/61158を参照してください – akarnokd

+0

RxJavaのバージョンを提供します。 –

+0

これはRxJava 1.2.6を使用しています - 私は質問を更新します –

答えて

4

これは、Agencyオブジェクトへのアクセスを与えるflatMapIterableが欠けていたことを利用して解決されました。

LaunchLibService service = ServiceFactory.createRetrofitService(LaunchLibService.class, LaunchLibService.SERVICE_ENDPOINT); 
     service.getAgencyList() 
       .subscribeOn(Schedulers.newThread()) 
       .observeOn(AndroidSchedulers.mainThread()) 
       .map(AgencyResponse::getAgencies) // Gets the List<Agency> but how do I iterate over each object 
       .flatMapIterable(agencyResponse -> agencyResponse) 
       .map(Agency::getName) 
       .subscribe(s -> textView.append(s + "\n")); 
関連する問題