RxJS and-thenDo-when example - operators

Dou you have a working example for me ? Which use-case can/should apply this pattern? The information here: http://reactivex.io/documentation/operators/and-then-when.html#collapseRxJS is very short.

Here is an example from the RxJS 4 docs:
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/thendo.md
var selector = function (x, y) { return x + ", " + y; };
var source = Rx.Observable.when(
Rx.Observable.interval(250).and(Rx.Observable.of("A", "B", "C")).thenDo(selector),
Rx.Observable.interval(300).and(Rx.Observable.of("a", "b")).thenDo(selector)
);
var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x);
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
// => Next: 0, A
// => Next: 0, a
// => Next: 1, B
// => Next: 1, b
// => Next: 2, C
// => Completed

Related

How to test concatenate streams in rxjs

The given class has a method which returns a cached stream but that stream can be triggered by another private hot stream which makes the cached stream emits a new value.
The class
export class SomeClass {
private cache: Observable<number>;
private trigger$ = new Subject();
private multiply = 1;
constructor(private num: number) {}
getNumber(): Observable<number> {
return (
this.cache ||
(this.cache = concat(of(void 0), this.trigger$).pipe(
switchMap(() => of(this.num * this.multiply++)),
shareReplay(1)
))
);
}
trigger(): void {
this.trigger$.next();
}
}
Example: https://stackblitz.com/edit/rxjs-gpyc46?file=index.ts
What is the way to test it?
This try is failed
it("trigger updates", () => {
testScheduler.run(({ expectObservable }) => {
const num$ = someClass.getNumber();
expectObservable(num$).toBe("a", { a: 3 });
someClass.trigger();
expectObservable(num$).toBe("a", { a: 6 });
someClass.trigger();
expectObservable(num$).toBe("a", { a: 9 });
});
});
Example: https://stackblitz.com/edit/rxjs-test-tricky-flow?file=src%2Fsome-class.spec.ts
UPD: so the problem here that seems it is not possible to mock the trigger$ property.
It would look like this
it("trigger updates", () => {
testScheduler.run(({ hot, expectObservable }) => {
spyOnProperty(someClass, 'trigger$', 'get').and.returnValue(hot('^--b--c'));
const num$ = someClass.getNumber();
expectObservable(num$).toBe("a--b--c", { a: 3, b: 6, c: 9 });
});
});
But the trigger$ property must be changed this way
get trigger$() {
return new Subject();
}
Example: https://stackblitz.com/edit/rxjs-test-tricky-flow-x2arxf?file=src%2Fsome-class.ts

Error in Vue — Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>` arrow-body-style

When adding a Vue.filter globally, the linter swears and I can’t understand how to fix this error:
Vue.filter('truncate', (text, length) => {
return text.length > length ? `${text.slice(0, length - 1)}...` : text;
});
I had the same issue. You have one statement so just put them in online like
Vue.filter('truncate', (text, length) => {return text.length > length ? `${text.slice(0, length - 1)}...` : text;
});
or it is more es6,
Vue.filter('truncate', (text, length) => (text.length > length ? `${text.slice(0, length - 1)}...:` text;
);
more info refer to link
for example,
incorrect code
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
let foo = () => {
return 0;
};
let foo = () => {
return {
bar: {
foo: 1,
bar: 2,
}
};
};
correct code
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
let foo = () => 0;
let foo = (retv, name) => {
retv[name] = true;
return retv;
};
let foo = () => ({
bar: {
foo: 1,
bar: 2,
}
});
let foo = () => { bar(); };
let foo = () => {};
let foo = () => { /* do nothing */ };
let foo = () => {
// do nothing.
};
let foo = () => ({ bar: 0 });
source

componentDidMount() : call function after getItem from asyncStorage

I have to send an codeActivation with my API after calling this codeActivation from asyncStorage so I use this code:
componentDidMount() {
AsyncStorage.getItem(CODEACTIVATION_STORED)
.then(code => {
this.setState({ codeActivation: code})
console.log('t2 ' + this.state.codeActivation); << output : t1 544875962
});
AsyncStorage.getItem(TOKEN_STORED)
.then(code => {
this.setState({ Token: code})
});
console.log('t1 ' + this.state.codeActivation); << output: t1
this.pwHash(); << where I use this.state.codeActivation
}
how to call pwHash after setting my codeActivation from asyncStorage in this.state.codeActivation ?
componentDidMount() {
setInterval(() => {
AsyncStorage.getItem(CODEACTIVATION_STORED)
.then(code => {
this.setState({ codeActivation: code})
console.log('t2 ' + this.state.codeActivation); << output : t1 544875962
});
AsyncStorage.getItem(TOKEN_STORED)
.then(code => {
this.setState({ Token: code})
console.log('t1 ' + this.state.codeActivation); << output: t1
this.pwHash(); << where I use this.state.codeActivation && this.state.token
});
}, 5000);
}
you can call it like this or you can just ignore setInterval() if that is not you need.

Couldn't read accelerometer and gyro from sensortag using react-native

I have been working on react-native-ble-plx with sensortag cc2650stk and having issues fetching accelerometer and gyro data.
Error: Characteristic "f000aa82-0451-4000-b000-000000000000" write failed for device xxxxxx and service "f000aa80-0451-4000-b000-000000000000"
Things work fine for all the other sensors of the ticc2650 sensortag. like humidity,temperature,barometer etc.
constructor() {
super();
this.manager = new BleManager()
this.state = {info: "", values: {}}
this.prefixUUID = "f000aa"
this.suffixUUID = "-0451-4000-b000-000000000000"
this.sensors = {
0: "Temperature",
8: "Accelerometer",
2: "Humidity",
7: "Magnetometer",
4: "Barometer",
// 5: "Gyroscope"
}
}
serviceUUID(num) {
return this.prefixUUID + num + "0" + this.suffixUUID
}
notifyUUID(num) {
return this.prefixUUID + num + "1" + this.suffixUUID
}
writeUUID(num) {
return this.prefixUUID + num + "2" + this.suffixUUID
}
My sensortag Movemnet UUIDS are:
MOVEMENT_SERVICE = 'f000aa80-0451-4000-b000-000000000000';
MOVEMENT_DATA = 'f000aa81-0451-4000-b000-000000000000';
MOVEMENT_CONFIG = 'f000aa82-0451-4000-b000-000000000000';
MOVEMENT_PERIOD = 'f000aa83-0451-4000-b000-000000000000';
MOVEMENT_NOTIFICATION = '00002902-0000-1000-8000-00805f9b34fb';
if (device.name === 'CC2650 SensorTag' || device.name === 'SensorTag') {
this.info("Connecting to TI Sensor")
this.manager.stopDeviceScan();
device.connect()
.then((device) => {
this.info("Discovering services and characteristics")
return device.discoverAllServicesAndCharacteristics()
})
.then((device) => {
this.info("Setting notifications")
console.log(device);
return this.setupNotifications(device)
})
.then(() => {
this.info("Listening...")
}, (error) => {
this.error(error.message)
})
}
async setupNotifications(device) {
for (const id in this.sensors) {
//id = 8;
const service = this.serviceUUID(id);
const characteristicW = this.writeUUID(id);
const characteristicN = this.notifyUUID(id);
const characteristic = await device.writeCharacteristicWithResponseForService(
service, characteristicW, "AQ==" /* 0x01 in hex */
)
device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
if (error) {
this.error(error.message)
return
}
console.log(characteristic.uuid+":::"+characteristic.value);
this.updateValue(characteristic.uuid, characteristic.value)
})
}
}
work fine for other sensors but not gyro and accelerometer.
Things work fine for other sensors when we write "AQ==" / 0x01 in hex / But for movement sensor we need to add "MDE=" for 0x01 in function for notifications
const characteristic = await device.writeCharacteristicWithResponseForService(
service, characteristicW, "AQ==" /* 0x01 in hex */
)
I dont know why have they done so but this solved the issue for me.

SQL tedious add array as parameter

I'm running this SQL query with tedious.js using parameters:
var query = "select * from table_name where id in (#ids)";
request = new sql.Request(query, function(err, rowCount) {
if (err) {
}
});
request.on('row', function(columns) {
});
var id = [1, 2, 3];
request.addParameters('ids', TYPES.Int, id);
connection.execSql(request);
because I am looking for items that matches the ID provided with where ... in ... clause, I need to pass in an array. However, there is no TYPES.Array. How do I this properly?
for this query, i think you'll just have to manually build the entire sql string. the TYPES enum values are for the datatypes in the database, not in your JavaScript code.
//you can like this:
var userIds = result.map(function (el) {
return el.UserId;
}).join(',');
var params = [{
name: 'userIds',
type: TYPES.VarChar,
value: userIds,
options: null}];
var querySql = ['SELECT COUNT([MomentId]) FROM [T_Moment]',
'WHERE [RecordStatus] = ', sysConst.recordStatus.activation, " AND CHARINDEX(','+RTRIM([UserId])+',' , ','+ #userIds +',')>0 "].join(' ');
dbHelper.count(querySql, params, function (err, result) {
if (err) {
callback('error--');
} else {
callback(null, result);
}
});
Try creating the in clause parameters for query dynamically.
// create connection
let ids = [1, 2, 3];
let inClauseParamters = createInClauseParameters();
let query = `select * from table_name where id in (${inClauseParamters})`;
let request = new Request(query, (err, rowCount) => {
if (err) { /* handle error */ }
});
request.on('row', (columns) => { /* get row */});
request = addRequestParameters(ids, request);
connection.execSql(request);
function createInClauseParameters(values) {
return values.map((val, index) => `#Value${index}`).join(',');
}
function addRequestParameters(values, request) {
values.forEach((val, index) => {
request.addParameter(`Value${index}`, TYPES.VarChar, val);
});
return request;
}