RxJava

ZiziChou

同步

(Synchronous)

異步(Asynchronous)

AsyncTask?Thread?Handler?

簡潔

new Thread() {
@Override
    public void run() {
        super.run();
        for (Folder folder : folders) {
            File[] files = folder.listFiles();
            for (File file : files) {
                if (file.getName().endsWith(".jpg")) {
                   Bitmap bitmap = getBitmapFromFile(file);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            galleryView.addImage(bitmap);
                        }
                    });
                }
            }
        }
    }
}.start();
Observable.from(folders)
    .flatMap(new Func1<File, Observable<Folder>>() {
        @Override
        public Observable<File> call(Folder folder) {
            return Observable.from(folder.listFiles());
        }
    })
    .filter(new Func1<File, Boolean>() {
        @Override
        public Boolean call(File file) {
            return file.getName().endsWith(".jpg");
        }
    })
    .map(new Func1<File, Bitmap>() {
        @Override
        public Bitmap call(File file) {
            return getBitmapFromFile(file);
        }
    })
    .subscribe(new Action1<Bitmap>() {
        @Override
        public void call(Bitmap bitmap) {
            galleryView.addImage(bitmap);
        }
    });
Observable.from(folders)
    .flatMap((Func1) (folder) -> { Observable.from(folder.listFiles()) })
    .filter((Func1) (file) -> { file.getName().endsWith(".jpg") })
    .map((Func1) (file) -> { getBitmapFromFile(file) })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe((Action1) (bitmap) -> { galleryView.addImage(bitmap) });

Retrolambda(optional)

被觀察者

觀察者

逮補

做壞事

Button

OnClickListener

onClick(View)

被觀察者

觀察者

事件

setOnClickListener()

訂閱

onEvent(params)

被觀察者

觀察者

事件

subscribe

訂閱

Observable

Observer

RxJava

onError

onNext(相當於 onClick / onEvent)

onCompleted

Observer

觀察者

決定事件觸發時將有怎樣的行為

Observer<String> observer = new Observer<String>() {
    @Override
    public void onNext(String name) {
        Log.d(tag, "Item Name: " + name);
    }

    @Override
    public void onCompleted() {
        Log.d(tag, "Completed!");
    }

    @Override
    public void onError(Throwable e) {
        Log.d(tag, "Error!");
    }
};

Observable

被觀察者

決定什麼時候觸發事件以及觸發怎樣的事

Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
    @Override
    public void call(Subscriber<? super String> subscriber) {
        subscriber.onNext("Hello");
        subscriber.onNext("Hi");
        subscriber.onNext("Aloha");
        subscriber.onCompleted();
    }
});

Operators

運算元

Creating

  • create
  • from
  • just

Transforming

  • map
  • flatMap

Filtering

Combining

Error Handling

Map

Observable.just("images/mamilove.png") // String
    .map(new Func1<String, Bitmap>() {
        @Override
        public Bitmap call(String filePath) { // String
            return getBitmapFromPath(filePath); // Bitmap
        }
    })
    .subscribe(new Action1<Bitmap>() {
        @Override
        public void call(Bitmap bitmap) { // Bitmap
            showBitmap(bitmap);
        }
    });

flatMap()

Student[] students = ...;

Observable.from(students)
    .map(new Func1<Student, String>() {
        @Override
        public String call(Student student) {
            return student.getName();
        }
    })
    .subscribe(new Observer<String>() {
        @Override
        public void onNext(String name) {
            Log.d(tag, name);
        }
        ...
    }
);
Student[] students = ...;

Observable.from(students)
    .subscribe(new Observer<Student>() {
        @Override
        public void onNext(Student student) {
            List<Course> courses = student.getCourses();
            for (int i = 0; i < courses.size(); i++) {
                Course course = courses.get(i);
                Log.d(tag, course.getName());
            }
        }
        ...
    }
);
Student[] students = ...;

Observable.from(students)
    .flatMap(new Func1<Student, Observable<Course>>() {
        @Override
        public Observable<Course> call(Student student) {
            return Observable.from(student.getCourses());
        }
    })
    .subscribe(new Observer<Course>() {
        @Override
        public void onNext(Course course) {
            Log.d(tag, course.getName());
        }
        ...
    }
);

Retrofit

@GET("/user")
public void getUser(@Query("userId") String userId, Callback<User> callback);
getUser(userId, new Callback<User>() {
    @Override
    public void success(User user) {
        userView.setUser(user);
    }

    @Override
    public void failure(RetrofitError error) {
        // Error handling
        ...
    }
};
@GET("/user")
public Observable<User> getUser(@Query("userId") String userId);
getUser(userId)
    .subscribe(new Observer<User>() {
        @Override
        public void onNext(User user) {
            userView.setUser(user);
        }
    });
getUser(userId, new Callback<User>() {
    @Override
    public void success(User user) {
        new Thread() {
            @Override
            public void run() {
                processUser(user);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        userView.setUser(user);
                    }
                });
            }).start();
    }
};
getUser(userId)
    .doOnNext(new Action1<User>() {
        @Override
        public void call(User user) {
            processUser(user);
        })

    .subscribe(new Observer<User>() {
        @Override
        public void onNext(User user) {
            userView.setUser(user);
        }
    });
Made with Slides.com