package com.oo.seex.netlibrary.net.response;


import com.app.baselibrary.base.exception.ServerException;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Rxjava 预处理返回结果；
 */

public class RxHelper {

    /**
     * 对服务器返回数据进行预处理
     *
     * @param <T>
     * @return
     */
    public static <T> Observable.Transformer<IResponse<T>, T> handleResult() {
        return new Observable.Transformer<IResponse<T>, T>() {
            @Override
            public Observable<T> call(Observable<IResponse<T>> tObservable) {
                return tObservable.flatMap(new Func1<IResponse<T>, Observable<T>>() {
                    @Override
                    public Observable<T> call(IResponse<T> result) {
                        if (result.isSuccess()) {
                            return createData(result.getResultData());
                        } else {
                            return Observable.error(new ServerException(result.getResultMssage()));
                        }
                    }
                }).subscribeOn(Schedulers.io());
            }
        };

    }

    /**
     * 创建成功的数据
     *
     * @param data
     * @param <T>
     * @return
     */
    private static <T> Observable<T> createData(final T data) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(data);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        });

    }
}
