package com.gingersoft.gsa.cloud.common.rxjava;

import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;
import com.xuexiang.rxutil2.rxjava.SchedulerTransformer;
import com.xuexiang.rxutil2.rxjava.scheduler.SchedulerType;
import java.util.concurrent.Executor;
import io.reactivex.Single;
import io.reactivex.SingleTransformer;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @作者: bin
 * @創建時間: 2021-04-17 15:10
 * @更新時間: 2021-04-17 15:10
 * @描述:自定义Single线程调度器
 */
public class MyRxSchedulerUtils {

    public static Scheduler io() {
        return io(RxSchedulerUtils.getIOExecutor());
    }

    public static Scheduler io(Executor executor) {
        return executor != null ? Schedulers.from(executor) : Schedulers.io();
    }

    private MyRxSchedulerUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 回到主线程
     *
     * @param single 被观察者
     */
    public static <T> Single<T> toMain(Single<T> single) {
        return single.observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 回到io线程
     *
     * @param single 被观察者
     */
    public static <T> Single<T> toIo(Single<T> single) {
        return single.observeOn(Schedulers.io());
    }

    /**
     * 订阅发生在主线程 （  ->  -> main)
     * 使用compose操作符
     *
     * @param <T>
     * @return
     */
    public static <T> SingleTransformer<T, T> _main_f() {
        return new SchedulerTransformer<>(SchedulerType._main);
    }

    /**
     * 订阅发生在io线程 （  ->  -> io)
     * 使用compose操作符
     *
     * @param <T>
     * @return
     */
    public static <T> SingleTransformer<T, T> _io_f() {
        return new SchedulerTransformer<>(SchedulerType._io);
    }

    /**
     * 处理在io线程，订阅发生在主线程（ -> io -> main)
     *
     * @param <T>
     * @return
     */
    public static <T> SingleTransformer<T, T> _io_main_f() {
        return new SchedulerTransformer<>(SchedulerType._io_main);
    }

    /**
     * 处理在io线程，订阅也发生在io线程（ -> io -> io)
     *
     * @param <T>
     * @return
     */
    public static <T> SingleTransformer<T, T> _io_io_f() {
        return new SchedulerTransformer<>(SchedulerType._io_io);
    }



}
