How do I use the RXJS selector function in the Observable.bindCallback method?

自作多情 提交于 2020-01-17 06:00:33

问题


I believe that to get two params properly mapped back to the callback when using Observable.bindCallback method you have to use the "selector" function, but I cannot find documentation that explains how to do this. I may have a misunderstanding of what the selector function does, but it still should be documented.

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindCallback

function testLogin(username, password, callback){
    // ...
    callback(param1, param2);
}

function selectorFunction(???) {
    // ???
}

function onTestLoginComplete(param1, param2) {
     // ...
}

var observableFactory = Observable.bindCallback(testLogin, selectorFunction);
var observable = observableFactory('username', 'password');
observable.subscribe( (param1, param2) => onTestLoginComplete(param1, param2) );

回答1:


The subscribe function can only ever take a single argument. So the selector function is about converting a multiargument callback into a single element. In general this means that you will pack the arguments into an object, and you can destructure it later on:

function testLogin(username, password, callback){
    // ...
    callback(param1, param2);
}

//Convert this into a new object
function selectorFunction(param1, param2) {
    return {param1, param2};
}

function onTestLoginComplete(param1, param2) {
     // ...
}

var observableFactory = Observable.bindCallback(testLogin, selectorFunction);
var observable = observableFactory('username', 'password');
//De-structure the argument when it is passed to subscribe.
observable.subscribe( ({param1, param2}) => onTestLoginComplete(param1, param2) );


来源:https://stackoverflow.com/questions/38275226/how-do-i-use-the-rxjs-selector-function-in-the-observable-bindcallback-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!