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

简介: RxAndroid和RxJava结合OkGo示例请求网络图片加载到不同ImageView代码:package zhangphil.


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:+'    //版本号使用 + 可以自动引用最新版


运行结果如图:


致谢:

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

相关文章
|
5月前
|
机器学习/深度学习 PyTorch 算法框架/工具
目标检测实战(一):CIFAR10结合神经网络加载、训练、测试完整步骤
这篇文章介绍了如何使用PyTorch框架,结合CIFAR-10数据集,通过定义神经网络、损失函数和优化器,进行模型的训练和测试。
291 2
目标检测实战(一):CIFAR10结合神经网络加载、训练、测试完整步骤
|
2月前
|
前端开发 小程序 Java
uniapp-网络数据请求全教程
这篇文档介绍了如何在uni-app项目中使用第三方包发起网络请求
100 3
|
2月前
|
Ubuntu Linux 开发者
Ubuntu20.04搭建嵌入式linux网络加载内核、设备树和根文件系统
使用上述U-Boot命令配置并启动嵌入式设备。如果配置正确,设备将通过TFTP加载内核和设备树,并通过NFS挂载根文件系统。
137 15
|
4月前
|
网络安全 Python
Python网络编程小示例:生成CIDR表示的IP地址范围
本文介绍了如何使用Python生成CIDR表示的IP地址范围,通过解析CIDR字符串,将其转换为二进制形式,应用子网掩码,最终生成该CIDR块内所有可用的IP地址列表。示例代码利用了Python的`ipaddress`模块,展示了从指定CIDR表达式中提取所有IP地址的过程。
106 6
|
6月前
|
缓存 网络协议 CDN
在网页请求到显示的过程中,如何优化网络通信速度?
在网页请求到显示的过程中,如何优化网络通信速度?
219 59
|
4月前
|
缓存 JavaScript
Vue加载网络组件(远程组件)
【10月更文挑战第23天】在 Vue 中实现加载网络组件(远程组件)可以通过多种方式来完成。
|
6月前
|
数据采集 Web App开发 开发工具
|
6月前
|
数据安全/隐私保护
|
6月前
|
小程序 开发者
微信小程序之网络数据请求 wx:request的简单使用
这篇文章介绍了微信小程序中如何使用wx.request进行网络数据请求,包括请求的配置、请求的格式以及如何在开发阶段关闭请求的合法检验。
微信小程序之网络数据请求 wx:request的简单使用
|
6月前
|
JSON API 开发者
Python网络编程新纪元:urllib与requests库,让你的HTTP请求无所不能
【9月更文挑战第9天】随着互联网的发展,网络编程成为现代软件开发的关键部分。Python凭借简洁、易读及强大的特性,在该领域展现出独特魅力。本文介绍了Python标准库中的`urllib`和第三方库`requests`在处理HTTP请求方面的优势。`urllib`虽API底层但功能全面,适用于深入控制HTTP请求;而`requests`则以简洁的API和人性化设计著称,使HTTP请求变得简单高效。两者互补共存,共同推动Python网络编程进入全新纪元,无论初学者还是资深开发者都能从中受益。
82 7

热门文章

最新文章