I'm trying to convert an Angular function to the observable pattern since it's current implementation has some asynchronicity to it. For the purposes of this discussion, take this simple example.
aFunction(x: boolean){
if(x){
// ... do something asynchronous based on the value of x
}
}
Converting it to use an Observable could be done in this manner:
anObservableFunction(x: boolean): Observable<any> {
const result = new Subject();
if(x){
// ... do something asynchronous based on the value of x
// ... where once the actual value you want to return to
// the subscribing functions, you can pass in the
// result.next(value);
// result.complete();
}
return result.asObservable();
}
The issue I'm facing (from my understanding) is catering for the instance where the inner selection statement isn't accessed.
anObservableFunction(x: boolean): Observable<any> {
const result = new Subject();
if(x){
// ... do something asynchronous based on the value of x
// ... where once the actual value you want to return to
// the subscribing functions, you can pass in the
// result.next(value);
// result.complete();
} else {
// here
}
return result.asObservable();
}
If a regular Subject is used, surely the subscribing functions will not get any value since the order of events would be:
- Function is called
- Subject is created
- Value is set
- Calling function subscribes, thus only getting values after this event occurring
And if a BehaviorSubject or ReplaySubject are used, their initial/constructed value will be retained, causing a subscription event to fire unnecessarily?
Observable.defer(() => x ? asyncOperation() : syncObservable())
- Ingo Bürk