I have a function loadMessages, I want it return an Observable.
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
return Observable.of(messages); // here return is not for this function, which is useless
}
});
console.log('3'); // I don't want this line run immediately
// I wish I can return here, but I cannot
}
How can I return to the function level?
Also, right now the order is 1 -> 3 -> 2. Is there any way to run 1 -> 2, and wait there until I get the data?
You can try something like this:
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
return Observable.create(observer => {
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
observer.next(messages)
}
});
});
}
Very simple example is here http://plnkr.co/edit/GADtB8QCTnNubtRu9SFv?p=preview
Related
I need to handle a situation where I have 3 endpoints to call and would like to get the data in the most convenient/efficient way. The first call can be handled independently and returns a single result. The second endpoint returns a collection but will need to initiate 0-* subsequent calls, where a given key is present.
Ideally would like to receive the collection (from the 2nd endpoint call) as a mutated/new collection that includes the result from the 3rd endpoint call.
I am currently using forkJoin(observableA$, observableB$) to handle the first 2 calls in parallel but I cannot work out how to include the sequential calls and have the data included in observableB$
//Customer observable
const customer$ = this._customerManagementService.getCustomer(
accountNumber
);
return forkJoin({
customer: customer$,
saleCycles: saleCyclesWithVehicle$
}).pipe(finalize(() => this._loaderFactoryService.hide()));
getSalesWithVehicle(accountNumber: string, dealerKey: string) {
return this._salesCycleService
.getCyclesForCustomer({
customerNumber: accountNumber,
dealerKey: dealerKey
})
.pipe(
concatMap((results: ISaleCycle[]) => {
return results.map(cycle => {
return this._purchaseVehicleService.getPurchaseVehicle(
cycle.vehicleKey
);
});
})
);
}
I expect the collection to include further data as a new property on the original collection
UPDATE
After a bit more thought maybe I should be using reduce somewhere in the solution. This way I can be in control of what's getting push into the array and it could be dynamic?
getSalesWithVehicle(accountNumber: string, dealerKey: string) {
return this._salesCycleService
.getCyclesForCustomer({
customerNumber: accountNumber,
dealerKey: dealerKey
})
.pipe(
switchMap((results: ISaleCycle[]) => {
return results.map(cycle => {
if (cycle.vehicleKey) {
return this._purchaseVehicleService
.getPurchaseVehicle(cycle.vehicleKey)
.pipe(
reduce((acc, vehicle) => {
return { cycle: cycle, vehicle: vehicle };
}, []),
toArray()
);
}
else {
///No extra data to be had
}
});
}),
concatAll()
);
}
I would use concatMap() to merge the responses of HTTP requests 2 and 3.
import { of } from 'rxjs';
import { map, concatMap } from 'rxjs/operators';
const pretendGetCustomer = of({accountNumber: 123, name:"John Doe"});
const pretendGetVehiculeHttpRequest = (customerNumber) => {
return of([{custNum: 123, vehicleId:"2"}, {custNum: 123, vehicleId:"1"}]);
}
const pretendGetCyclesHttpRequest = (cycleIds) => {
return of([{id:"1", name:"yellow bike", retailPrice:"$10"}, {id:"2", name:"red bike", retailPrice:"$20"}]);
}
const yourFunction = () => {
pretendGetCustomer.subscribe(customer => {
// Assuming you do other things here with cust, reason why we are subscribing to this separately
// isHappy(customer)
// Your second & third calls
pretendGetVehiculeHttpRequest(customer.accountNumber).pipe(
// Need to use concatMap() to subscribe to new stream
// Note: use mergeMap() if you don't need the 1st stream to be completed
// before calling the rest
concatMap(purchases => {
const cyclesIds = purchases.map(p => p.vehicleId);
// concatMap() requires an Observable in return
return pretendGetCyclesHttpRequest(cyclesIds).pipe(
// Use map() here because we just need to use the data,
// don't need to subscribe to another stream
map(cycles=>{
// Retrun whatever object you need in your subscription
return {
customerNumber: customer.accountNumber,
customerName: customer.name,
purchases: purchases.map(p => cycles.find(c => p.vehicleId === c.id))
}
})
);
})
).subscribe(resultof2and3 => {
// Do something with the new/mutated Object which is a result of
// your HTTP calls #2 and #3
console.log(resultof2and3);
});
});
}
yourFunction();
I made a stackblitz if you want to see the above run (see console): https://stackblitz.com/edit/rxjs-nqi7f1
This is the solution I eventually came up with. I've taken the advice from BoDeX and used concatMap(). In my mind it was clear that I wanted to use forkJoin and be able to reference the results by object key, I.e customer or saleCycles.
In the scenario where a vehicleKey was present I needed to return the results in a defined data structure, using map(). Likewise, if no vehicle was found then I just needed the outer observable.
const customer$ = this._customerManagementService.getCustomer(accountNumber);
const saleCyclesWithVehicle$ = this.getSalesWithVehicle(accountNumber,dealerKey);
getSalesWithVehicle(accountNumber: string, dealerKey: string) {
return this._salesCycleService
.getCyclesForCustomer({
customerNumber: accountNumber,
dealerKey: dealerKey
})
.pipe(
concatMap(cycles => {
return from(cycles).pipe(
concatMap((cycle: ISaleCycle) => {
if (cycle.vehicleKey) {
return this._purchaseVehicleService
.getPurchaseVehicle(cycle.vehicleKey)
.pipe(
map(vehicle => {
return { cycle: cycle, vehicle: vehicle };
})
);
} else {
return of({ cycle: cycle });
}
}),
toArray()
);
})
);
}
return forkJoin({
customer: customer$,
saleCycles: saleCyclesWithVehicle$
}).pipe(finalize(() => this._loaderFactoryService.hide()));
I'm trying to fix a problem from the code and don't understand why is not working.
Function:
export const monthlyKpiActions_disp = (threeMonthsBefore, currentDate) => {
console.log('kpppppppppppppppi')
return monthlyKpiActions.fetch({
filter: {
objectId,
interval: threeMonthsBefore + '/' + currentDate,
names: [
'ecostats_fuelusagetotal',
'ecostats_fuelrefmileage',
'ecostats_co2emission',
'tripstats_mileage',
'tripstats_drivingtime',
'optidrive_indicator_8'
].join(',')
},
forceUpdate: true,
resetState: false
})
}
redux
function mapDispatchToProps(dispatch) {
return {
monthlyKpiActions_func: (threeMonthsBefore, currentDate) => dispatch(monthlyKpiActions_disp(threeMonthsBefore, currentDate)),
}
}
calling the function
const currentDate = moment.utc().add(1, 'months').format(dateFormat)
const threeMonthsBefore = moment.utc().subtract(3, 'months').format(dateFormat)
{ () => this.props.monthlyKpiActions_func(threeMonthsBefore, currentDate) }
The problem is that never enters the function, any suggestions?
That's because you never call the action, this line
{ () => this.props.monthlyKpiActions_func(threeMonthsBefore, currentDate) }
Creates a block scope with an anonymous function which internally calls your action, but its never invoked (nor makes any sense in this context).
Just call the action:
this.props.monthlyKpiActions_func(threeMonthsBefore, currentDate)
i'm trying to add persistent attributes to my lambda function.
i created a dynamoDB table and added it to the triggers of my lambda function.
i copied a sample code from github, but when i try to launch the skill i get an error. The console log shows:
{
"errorMessage": "Could not read item (amzn1.ask.account.AGIIYNRXWDLBD6XEPW72QS2BHGXNP7NWYBEWSH2XLSXZP64X3NCYEMVK233VFDWH77ZB6DAK6YJ53SZLNUFVQ56CYOVCILS7QFZI4CIRDWC3PAHS4QG27YUY5PTT6QEIK46YFNTJT54YAKNGOWV2UO66XZACFDQ5SEXKJYOBNFNIZNUXKNTIAAYZG4R5ZU4FMLPDZZN64KLINNA) from table (Spiele): The provided key element does not match the schema",
"errorType": "AskSdk.DynamoDbPersistenceAdapter Error",
"stackTrace": [
"Object.createAskSdkError (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/utils/AskSdkUtils.js:22:17)",
"DynamoDbPersistenceAdapter.<anonymous> (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:123:49)",
"step (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:44:23)",
"Object.throw (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:25:53)",
"rejected (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:17:65)",
"<anonymous>",
"process._tickDomainCallback (internal/process/next_tick.js:228:7)"
]
}
the table contains a primary key "name" and sort key "UserId". is that wrong?
here is my index.js:
const Alexa = require('ask-sdk');
// Define the skill features
let skill;
/**
* If this is the first start of the skill, grab the user's data from Dynamo and
* set the session attributes to the persistent data.
*/
const GetUserDataInterceptor = {
process(handlerInput) {
let attributes = handlerInput.attributesManager.getSessionAttributes();
if (handlerInput.requestEnvelope.request.type === 'LaunchRequest' && !attributes['isInitialized']) {
return new Promise((resolve, reject) => {
handlerInput.attributesManager.getPersistentAttributes()
.then((attributes) => {
attributes['isInitialized'] = true;
saveUser(handlerInput, attributes, 'session');
resolve();
})
.catch((error) => {
reject(error);
})
});
}
}
};
function saveUser(handlerInput, attributes, mode) {
if(mode === 'session'){
handlerInput.attributesManager.setSessionAttributes(attributes);
} else if(mode === 'persistent') {
console.info("Saving to Dynamo: ",attributes);
return new Promise((resolve, reject) => {
handlerInput.attributesManager.getPersistentAttributes()
.then((persistent) => {
delete attributes['isInitialized'];
handlerInput.attributesManager.setPersistentAttributes(attributes);
resolve(handlerInput.attributesManager.savePersistentAttributes());
})
.catch((error) => {
reject(error);
});
});
}
}
const LaunchHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
},
handle(handlerInput) {
console.info("LaunchRequest");
let attributes = handlerInput.attributesManager.getSessionAttributes();
console.info("Test the load: " + attributes['isInitialized']);
attributes['FOO'] = "BAR";
saveUser(handlerInput, attributes, 'persistent');
return handlerInput.responseBuilder
.speak('Hello')
.reprompt('Hello')
.getResponse();
}
}
exports.handler = Alexa.SkillBuilders.standard()
.addRequestHandlers(
LaunchHandler
)
.addRequestInterceptors(GetUserDataInterceptor)
.withTableName('Spiele')
.withAutoCreateTable(true)
.withDynamoDbClient()
.lambda();
can anyone tell me what i'm doing wrong?
please confirm the partition key is 'userId' not 'UserId' (notice the uppercase U).
Also I would suggest using 'this' object.
Let me know if that helps.
Cheers
Below code is for python lambda function
from ask_sdk_core.skill_builder import CustomSkillBuilder
from ask_sdk_dynamodb.adapter import DynamoDbAdapter
sb = SkillBuilder()
sb = CustomSkillBuilder(persistence_adapter = dynamodb_adapter)
I am trying to return an observable inside an async arrow function passed to a flatMap, but the returned observable is not being called.
protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
return this.userRepository.getUserByName(params.getUsername())
.pipe(flatMap(async user => {
if (!user) {
throw new Error(Errors.USER_DOESNT_EXIST);
}
const match = await this.cypher.compare(params.getPassword(), user.password);
if (!match) {
throw new Error(Errors.WRONG_PASSWORD);
}
return Observable.create((subscriber: Subscriber<Session>) => {
subscriber.next(new Session("token test", "refreshToken test"));
subscriber.complete();
});
}));
}
Does anyone knows why does it happen and how can I solve it? Thanks in advance.
Solved, I just turned the promise into an observable and did flatMap it.
protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
return this.userRepository.getUserByName(params.getUsername())
.pipe(flatMap(storedUser => {
if (!storedUser) {
throw new Error(Errors.USER_DOESNT_EXIST);
}
return from(this.cypher.compare(params.getPassword(), storedUser.password));
})).pipe(flatMap(match => {
if (!match) {
throw new Error(Errors.WRONG_PASSWORD);
}
return Observable.create((subscriber: Subscriber<Session>) => {
subscriber.next(new Session("token test", "refreshToken test"));
subscriber.complete();
});
}));
}
I am looking for simply fetching an object as a JSON, not as an observable.
So far I could:
fbGetCarById(car_id: string){
var car_json;
var car_obs: FirebaseObjectObservable<any>;
car_obs = this.db.object('/cars/'+car_id, { preserveSnapshot: true });
car_obs.subscribe(snapshot => {
console.log(snapshot.val())
car_json = snapshot.val();
});
return car_json;
}
However, .subscribe is an async function which does not return the snapshot linearly, so everything ends a mess =/.
How can I simply look for an object and have a simple JSON object as a response?
You could return a Promise.
fbGetCarById(car_id: string):Promise<string>{
const promise = new Promise<string>((resolve,reject)=>{
var car_obs: FirebaseObjectObservable<any>;
car_obs = this.db.object('/cars/'+car_id, { preserveSnapshot: true });
car_obs.subscribe(snapshot => {
resolve(snapshot.value())
});
}
return promise;
}