OkHttpClient加载图片给DisposableObserver,CompositeDisposable调度控制后台任务队列简单代码

OkHttpClient加载图片给DisposableObserver,CompositeDisposable调度控制后台任务队列简单代码


实现一个简单的功能,点击按钮,触发OkHttpClient加载图片给DisposableObserver,然后刷新ListView。全程有CompositeDisposable控制任务队列。


布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>




Java代码:

package zhangphil.app;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity {

    private final String TAG = String.valueOf(UUID.randomUUID());

    private ArrayList mItems = new ArrayList<>();
    private ItemAdapter mAdapter;

    private OkHttpClient mOkHttpClient;

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mOkHttpClient = new OkHttpClient();

        mAdapter = new ItemAdapter(this, -1);
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(mAdapter);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://avatar.csdn.net/9/7/A/1_zhangphil.jpg";
                addItems(url);
            }
        });
    }

    private void addItems(final String url) {
        DisposableObserver disposableObserver = new DisposableObserver<Bitmap>() {

            @Override
            public void onNext(@NonNull Bitmap bmp) {
                Log.d(TAG, "onNext");
                mItems.add(bmp);
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "onComplete");
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, e.toString(), e);
            }
        };

        /**
         * 注意此处的写法!
         */
        mCompositeDisposable.add(
                getBitmapObservable(url)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(disposableObserver)
        );
    }


    /**
     * 以下是常规的Android ListView数据添加和更新Adapter
     */

    private class ItemAdapter extends ArrayAdapter {
        private Context context;

        public ItemAdapter(@NonNull Context context, @LayoutRes int resource) {
            super(context, resource);
            this.context = context;
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ImageView imageView = new ImageView(context);
            imageView.setImageBitmap(getItem(position));
            return imageView;
        }

        @Nullable
        @Override
        public Bitmap getItem(int position) {
            Bitmap bmp = (Bitmap) mItems.get(position);
            return bmp;
        }

        @Override
        public int getCount() {
            return mItems.size();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //取消所有Okhttp的网络请求
        mOkHttpClient.dispatcher().cancelAll();

        //如果退出程序,就清除后台任务
        mCompositeDisposable.clear();
    }


    private Observable<Bitmap> getBitmapObservable(@NonNull final String url) {
        return Observable.defer(new Callable<ObservableSource<Bitmap>>() {
            @Override
            public ObservableSource<Bitmap> call() throws Exception {
                Thread.sleep(5000);

                Bitmap bmp = null;

                //同步方法返回观察者需要的数据结果
                //在这里处理线程化的操作

                Request request = new Request.Builder().url(url).build();
                Response response = mOkHttpClient.newCall(request).execute();
                try {
                    if (response.isSuccessful()) {
                        byte[] bytes = response.body().bytes();
                        bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.d(TAG, "数据正确");

                return Observable.just(bmp);
            }
        });
    }
}


你可能感兴趣的:(java,android,rxandroid,rxjava)