如何在RxJava 2中使用Flowable?

时间:2016-08-29 13:50:02

标签: java android rx-java rx-android

RxJava2中引入了新的Flowable。如何在android中使用它。 RxJava1中没有Flowable。

2 个答案:

答案 0 :(得分:10)

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 SingleObserver<Integer> getObserver() {

     return new SingleObserver<Integer>() {
        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, " onSubscribe : " + d.isDisposed());
        }

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

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

我有一个示例项目来演示RxJava2的使用。在这里,您可以找到sample project - RxJava2-Android-Samples

答案 1 :(得分:1)

This is what it says in the documentations

Practically, the 1.x fromEmitter (formerly fromAsync) has been renamed to Flowable.create. The other base reactive types have similar create methods (minus the backpressure strategy).

So you can use this in the same way as fromEmitter and fromAsync

Rx.2 Documentation