anand gaurav anand gaurav - 3 months ago 194
Java Question

How to use Flowable in RxJava 2?

There is an introduction of new Flowable in RxJava2. How to use this in android. There was no Flowable in RxJava1.

Answer
public class FlowableExampleActivity extends AppCompatActivity {

    private static final String TAG = FlowableExampleActivity.class.getSimpleName();
    Button btn;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
        btn = (Button) findViewById(R.id.btn);
        textView = (TextView) findViewById(R.id.textView);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doSomeWork();
            }
        });
    }

    /*
     * simple example using Flowable
     */
    private void doSomeWork() {

        Flowable<Integer> observable = Flowable.just(1, 2, 3, 4);

        observable.reduce(50, new BiFunction<Integer, Integer, Integer>() {
            @Override
            public Integer apply(Integer t1, Integer t2) {
                return t1 + t2;
            }
        }).subscribe(getObserver());

    }

    private DefaultSubscriber<Integer> getObserver() {
        return new DefaultSubscriber<Integer>() {
            @Override
            public void onComplete() {
                textView.append(" onComplete");
                Log.d(TAG, " onComplete");
            }

            @Override
            public void onError(Throwable e) {
                textView.append(" onError : " + e.getMessage());
                Log.d(TAG, " onError : " + e.getMessage());
            }

            @Override
            public void onNext(Integer value) {
                textView.append(" onNext : value : " + value);
                Log.d(TAG, " onNext value : " + value);
            }
        };
    }
}

I have a create a sample project to demonstrate the use of RxJava2. Here you can find the sample project - RxJava2-Android-Samples

Comments