RxAndroid和RxJava结合OkGo示例请求网络图片加载到不同ImageView

来源:互联网 发布:linux tar只读权限 编辑:程序博客网 时间:2024/05/29 02:31


RxAndroid和RxJava结合OkGo示例请求网络图片加载到不同ImageView


代码:

package zhangphil.app;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.support.annotation.Nullable;import android.util.Log;import android.widget.ImageView;import android.widget.TextView;import com.lzy.okgo.OkGo;import java.util.ArrayList;import java.util.List;import java.util.UUID;import io.reactivex.Observable;import io.reactivex.android.schedulers.AndroidSchedulers;import io.reactivex.functions.Function;import io.reactivex.observers.DisposableObserver;import io.reactivex.schedulers.Schedulers;import okhttp3.Response;/** * 本例使用RxAndroid和RxJava,结合Okgo,在一个最普遍的应用场景, * 比如有两个ImageView,给每个ImageView请求给定的url,请求回Bitmap后,分别装载到相应的ImageView。 * 这种情况在实际的开发中十分常见,本利给出一个基本用法,由此可以举一反三变化出更多更复杂的用法。 * */public class MainActivity extends Activity {    private final String TAG = String.valueOf(UUID.randomUUID());    private DisposableObserver<MyItem> mObserver = new DisposableObserver<MyItem>() {        @Override        public void onNext(MyItem item) {            item.image.setImageBitmap(item.bitmap);            item.text.setText(item.url);        }        @Override        public void onComplete() {            Log.d(TAG, "onComplete");        }        @Override        public void onError(Throwable e) {            Log.e(TAG, e.toString(), e);        }    };    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ImageView image1 = (ImageView) findViewById(R.id.image1);        ImageView image2 = (ImageView) findViewById(R.id.image2);        TextView text1 = (TextView) findViewById(R.id.text1);        TextView text2 = (TextView) findViewById(R.id.text2);        String url1 = "http://avatar.csdn.net/9/7/A/1_zhangphil.jpg";        String url2 = "http://avatar.csdn.net/9/7/A/2_zhangphil.jpg";        List<MyItem> lists = new ArrayList<>();        MyItem i1 = new MyItem();        i1.image = image1;        i1.url = url1;        i1.text = text1;        lists.add(i1);        MyItem i2 = new MyItem();        i2.image = image2;        i2.url = url2;        i2.text = text2;        lists.add(i2);        Observable mObservable = Observable                .just(lists)                .flatMap(function)                .map(getBitmap)                .subscribeOn(Schedulers.io()) //执行任务的线程                .observeOn(AndroidSchedulers.mainThread()); //回调发生的线程        //建立订阅关系        mObservable.subscribe(mObserver);        //mObservable.subscribe(mConsumer);    }    private class MyItem {        public ImageView image;        public Bitmap bitmap;        public TextView text;        public String url;    }    private Function<MyItem, MyItem> getBitmap = new Function<MyItem, MyItem>() {        @Override        public MyItem apply(MyItem item) throws Exception {            //同步方法返回观察者需要的数据结果            //在这里处理线程化的操作            Response response = OkGo.get(item.url).tag(TAG).execute();            try {                if (response.isSuccessful()) {                    byte[] bytes = response.body().bytes();                    item.bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);                }            } catch (Exception e) {                e.printStackTrace();            }            return item;        }    };    // 设置映射函数    private Function<List<MyItem>, Observable<MyItem>> function = new Function<List<MyItem>, Observable<MyItem>>() {        @Override        public Observable<MyItem> apply(List<MyItem> lists) {            MyItem[] items = new MyItem[lists.size()];            for (int i = 0; i < lists.size(); i++) {                items[i] = lists.get(i);            }            return Observable.fromArray(items);        }    };    //如果只是接受处理结果,那么可以不用DisposableObserver,而用Consumer(消费)//    private Consumer mConsumer = new Consumer<Bitmap>() {//        @Override//        public void accept(Bitmap bmp) throws Exception {//            image.setImageBitmap(bmp);//        }//    };    @Override    protected void onDestroy() {        super.onDestroy();        OkGo.getInstance().cancelTag(TAG);    }}


布局文件:

<?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">    <ImageView        android:id="@+id/image1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal" />    <TextView        android:id="@+id/text1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textColor="@android:color/black" />    <View        android:layout_width="match_parent"        android:layout_height="50dp"        android:background="@android:color/holo_orange_light" />    <ImageView        android:id="@+id/image2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal" />    <TextView        android:id="@+id/text2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textColor="@android:color/black" /></LinearLayout>


不要忘记在build.gradle配置:

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'    compile 'io.reactivex.rxjava2:rxjava:2.0.1'    compile 'com.lzy.net:okgo:+'        //版本号使用 + 可以自动引用最新版    compile 'com.lzy.net:okserver:+'    //版本号使用 + 可以自动引用最新版


运行结果如图:


致谢:

冯祖学对本文有重大贡献!

0 0
原创粉丝点击