package com.danieldisu.rxjavaintro; import import import import import import import import
android.os.Bundle; android.support.v4.app.ListFragment; android.support.v7.app.AppCompatActivity; android.util.Log; android.view.Menu; android.view.MenuItem; android.widget.ArrayAdapter; android.widget.ListView;
import com.google.common.collect.Lists; import com.jakewharton.rxbinding.widget.RxAdapterView; import java.util.List; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private static String TAG = "RX_JAVA_INTRO"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListFragment listFragment = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.listFragment); RestClient.HNService hnService = RestClient.getHNService(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); listFragment.setListAdapter(adapter); hnService.getNewStories() .subscribeOn(Schedulers.io()) .map(newStories -> getItemObservables(hnService, newStories)) .flatMap(Observable::merge) .doOnNext(hnItem1 -> Log.d(TAG, "item received " + hnItem1.id)) .take(10) .observeOn(AndroidSchedulers.mainThread()) .subscribe((hnItem) -> addItemToList(hnItem, adapter), Throwable::printStackTrace); ListView listView = listFragment.getListView(); RxAdapterView.itemClicks(listView) .subscribe(position -> Log.d(TAG, "Item at position " + position + " pressed")); } private void addItemToList(RestClient.HNItem hnItem, ArrayAdapter<String> adapter) { adapter.add(hnItem.title); }
private List> getItemObservables(RestClient.HNService hnService, RestClient.NewStories newStories) { return Lists.transform(newStories, hnService::getItem); } }