RXJAVA实现生产者、消费者

直接上代码

package com.test;

import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView sample_text;
    FlowableEmitter flowableEmitter;
    Subscription subscription;
    Flowable<String> flowable = Flowable.create(new FlowableOnSubscribe<String>() {
        @Override
        public void subscribe(FlowableEmitter<String> e) throws Exception {
            flowableEmitter = e;
        }
    }, BackpressureStrategy.LATEST);


    Subscriber<String> subscriber = new Subscriber<String>() {

        @Override
        public void onSubscribe(Subscription s) {
            MainActivity.this.subscription = s;
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(String str) {
            SystemClock.sleep(1);
            // TODO:              
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
        sample_text = findViewById(R.id.sample_text);
        flowable.subscribeOn( AndroidSchedulers.mainThread()).observeOn( Schedulers.io()).subscribe(subscriber);
        sample_text.setOnClickListener(this);

    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    @Override
    public void onClick(View v) {
        //模拟生产数据
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i< 1000;i++){
                    try {
                        flowableEmitter.onNext("test"+i);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(subscription!=null){
            subscription.cancel();
        }

    }
}
发布了33 篇原创文章 · 获赞 20 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/huangwenkui1990/article/details/87094906