RxJava2Retrofit

package com.example.rxjava2retrofit;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private ImageView image;

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

        Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                e.onNext(getBitmap());
            }
        })
                //设置数据在子线程中运行
                .subscribeOn(Schedulers.io())
                //设置图片加载在主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        image.setImageBitmap(bitmap);
                    }
                });


    }

    private Bitmap getBitmap() {

        String str = "http://img.fulishe.com//images/201905/thumb_img/16776_thumb_G_1557984610441.jpeg";
        try {
            URL url = new URL(str);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(2000);
            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200){
                return BitmapFactory.decodeStream(urlConnection.getInputStream());
            }




        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    private void initView() {
        image = (ImageView) findViewById(R.id.image);
    }
}

你可能感兴趣的:(RxJava2Retrofit)