2016-11-17 99 views
1

我需要一種方法來將值從observable傳遞給兩個函數,每個函數接受一個值,然後每個函數返回一個可觀察值(僅發射一個值,然後完成)。我希望.combineLatest()可以讓我通過投影功能,但事實並非如此。RxJS5:.combineLatest()與投影函數?

示例代碼(不工作):

const ac = [1, 2, 3]; // only as example, I have complex types in my array not numbers 

Observable.from(ac) 
    .combineLatest(
     // processFn should get a number as argument and return Observable<number> 
     // does not work because .combineLatest does not accept two functions as arguments :(
     n => processFn1(n), 
     n => processFn2(n) 
    ) 
    .map(([result1, result2] => { 
     // result1, result2 should be flat numbers here, not Observables 
    }) 
); 

如何做到這一點任何想法?

回答

1

您的想法使用combineLatest操作符是正確的,但它在錯誤的地方。如果你需要平坦觀察者,你應該使用mergeMap。這是一個JSBIN已經做了你所期望的:http://jsbin.com/rutovot/4/edit?html,js,console

的代碼看起來是這樣的:

const ac = [1, 2, 3]; 

Rx.Observable.from(ac) 
    // use mergeMap, it takes a function that accepts a value and 
    // returns an observable. MergeMap will listen to this observable 
    // under the hood and next the result of this observable down the 
    // the chain 
    .mergeMap(val => { 
    // Here we return an observable that combines the result of the 
    // call to both the functions 
    return Rx.Observable.combineLatest(fake(val), fake2(val)); 
    }) 
    .subscribe(val => console.log(val)); 
+0

那麼微不足道,一旦你讀它:) – Dyna

+0

通常是RxJS但它需要一些時間來使用它:) – KwintenP