Observable - 开始有条件地发射

Observable - start to emit conditionally

有没有办法从可观察对象开始有条件地发射值?在我的例子中,.asObservable() 函数的订阅者应该只在 CurrentUser 初始化后获得第一个值。

export class CurrentUser {

    private currentUser$: Observable<CurrentUser>;
    private currentUserBehaviorSubject: BehaviorSubject<CurrentUser>;

    public name: string = "";

    constructor() {
        this.currentUserBehaviorSubject = new BehaviorSubject(this);
        this.currentUser$ = this.currentUserBehaviorSubject.asObservable();
    }

    public asObservable(): Observable<CurrentUser> {
        // 
        if(user.name.length > 0){
            return this.currentUser$;
        }
        else {
            // ?????
        }
    }

    public initialize(string name){
        this.name = name;
        this.currentUserBehaviorSubject.next(this);
    }
}

export class SampleComponent {
    constructor(
        currentUser: CurrentUser
    ) {
        currentUser.asObservable().subscribe(
            (u: CurrentUser) => {
                // i only want an INITIALIZED user here
            },
            error => {},
            () => { }
        );
    }
}

看起来你可以在你的 asObservable() 方法中总是 return 一个 Observable 并且只使用 skipUntil() 运算符抑制发射直到 currentUserBehaviorSubject 发射(我想这就是你知道 CurrentUser 已经被初始化):

public asObservable(): Observable<CurrentUser> {
    return this.currentUser$
        .skipUntil(this.currentUserBehaviorSubject);
}

我怎么看:

export class CurrentUser {
    subject: Subject<CurrentUser> = new Subject<CurrentUser>();
    observable: Observable<CurrentUser = this.subject.asObservable();

    constructor() {
        // Do your business
        this.subject.next(this);
    }
}

并且在您的组件中,只需订阅 observable 属性。

这样,当您初始化一个新的 CurrentUser 时,您的观察者会收到通知。这是你想要的,还是我误解了?