Reputation: 190
I'm trying to use RxJS to replace the next piece of code(jsbin):
function parseRequestUrl(url) {
var newUrl;
if ((newUrl = testThatUrlIsOrigin1(url)) !== url) {
return doSomething(newUrl);
}
if ((newUrl = testThatUrlIsOrigin2(url)) !== url) {
return doSomething(newUrl);
}
if ((newUrl = testThatUrlIsOrigin3(url)) !== url) {
return doSomething(newUrl);
}
}
Something i was able to achieve using RxJS(jsbin) but in that case i needed to call a function twice for which "filter expression" is true
function parseRequestUrl(url) {
var newUrl = url;
var observer = Rx.Observable.of(testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3);
observer.first(getUrlFunc => getUrlFunc(url) !== url).map(getUrlFunc => getUrlFunc(url)).subscribe(createdUrl => newUrl = createdUrl)
return doSomething(newUrl);
// And so on
}
Can RxJS suit my requirements ?
Upvotes: 0
Views: 395
Reputation: 5988
I don't think that RxJs is the right tool for the job. It is best suited for processing asynchronous streams of data. I think that a better approach would be to just put all of your test functions in an array and loop over them. Something like this:
const tests = [testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3];
function parseRequestUrl(url) {
for (const test of tests) {
const newUrl = test(url);
if (newUrl === url) continue;
return newUrl;
}
}
function testThatUrlIsOrigin1(url) {
console.log("try testThatUrlIsOrigin1");
if (url === 'origin1') {
console.log("Pass testThatUrlIsOrigin1");
return "First If";
}
return url;
}
function testThatUrlIsOrigin2(url) {
console.log("try testThatUrlIsOrigin2");
if (url === 'origin2') {
console.log("Pass testThatUrlIsOrigin2");
return "Second If";
}
return url;
}
function testThatUrlIsOrigin3(url) {
console.log("try testThatUrlIsOrigin3");
if (url === 'origin3') {
console.log("Pass testThatUrlIsOrigin3");
return "Third If";
}
return url;
}
parseRequestUrl('origin2')
You could also implement the Chain of Responsibility design pattern if you wanted to get all OO on it.
EDIT Since you want to see how to do it in RxJs, here is a simplified version:
function test(a, b) {
return a === b ? `${a} test` : b;
}
const tests = [
test.bind(null, 1),
test.bind(null, 2),
test.bind(null, 3),
];
const value = 2;
Rx.Observable.from(tests)
.map(x => x(value))
.filter(x => x !== value)
.take(1)
.subscribe(
x => { console.log(x); },
null,
() => { console.log('completed'); }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>
Upvotes: 4