package cn.reghao.tnb.user.app.hystrix.observable;

import cn.reghao.tnb.user.app.service.UserServiceHystrix;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import rx.Observable;
import rx.Subscriber;

/**
 * 使用HystrixObservableCommand时，默认会使用信号量隔离
 * 甚至连线程池都不能控制了
 *
 * @author reghao
 * @date 2025-07-23 17:54:37
 */
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class HaloSemaphoreIsolationCommand extends HystrixObservableCommand<String> {
    private final UserServiceHystrix userServiceHystrix;

    public HaloSemaphoreIsolationCommand(UserServiceHystrix userServiceHystrix) {
        super(HystrixCommandGroupKey.Factory.asKey("HaloGroup"));
        this.userServiceHystrix = userServiceHystrix;
    }

    @Override
    protected Observable<String> construct() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> observer) {
                try {
                    if (!observer.isUnsubscribed()) {
                        // a real example would do work like a network call here
                        String s = userServiceHystrix.getResult();
                        observer.onNext(s);
                        observer.onCompleted();
                    }
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        });
    }
}
