I'm trying to make a subscription Hub with starting value. I cant set the starting value.
Now i have observable which generates DateTime.UtcNow in every 30 minutes interval.
public async Task Subscribe()
{
var client = Clients.Client(Context.ConnectionId);
var subscription = new CompositeDisposable();
var dateTimeUTCNow = Observable.Interval(TimeSpan.FromMinutes(30))
.Subscribe(#event =>
{
client.SendAsync("newDateTimeUtc", DateTime.UtcNow);
});
subscription.Add(dateTimeUTCNow);
RegisterHandler(subscription, userFound.UserToken);
}
I must to set starting value - DateTime.NowUtc
Are you looking for the StartWith operator?
Observable
.Interval(TimeSpan.FromMinutes(30))
.Select(_ => DateTime.UtcNow)
.StartWith(DateTime.UtcNow)
...
You can use the .Timer(TimeSpan dueTime, TimeSpan period) overload, instead of the Interval operator.
If you set dueTime to TimeSpan.Zero it will emit the first item at subscription time.
Observable
.Timer(TimeSpan.Zero, TimeSpan.FromMinutes(30))
.Select(_ => DateTime.UtcNow)
...
As gitbox mentioned you can also use StartWith. However StartWith will give you the declaration time instead of subscription time. If declaration time and subscription time are the same, there will of course be no difference.
Related
I'm using ngrx/component-store and loving it so far. Having prior store knowledge building my own simple ones, the only real headache I've had so far is when I've had to update an array and figured out I have to always create a new one for the internal compare() pipe to realize the array got updated.
Anyway, reading through the documentation it talks about updater methods and patchState. To me they do exactly the same thing, but their creation is slightly different. You would call patchState inside of a method while this.updater() returns a method giving you a function you can expose in your service. Anytime I'm updating my state it's always after a network call. I assume there are plenty of scenarios where you'd want to update your state without a network call so this is why you would want to have an updater available to your component to call. The question is if an updater and patchState are really doing the same thing then is it a better practice to call an updater in an effect or use patchState, or maybe am I putting too much logic in my effect?
On a side note, the docs say an updater method is supposed to be a pure function. If you're using it to your push an object onto an array then is it really pure?
// adding the selectors so people know what components are subscribing to
readonly approvals$ = this.select(state => state.requestApprovals);
readonly registration$ = this.select(state => state);
readonly updateAssessment = this.effect(($judgement: Observable<{id: string, isApproved: boolean}>) => {
return $judgement.pipe(
switchMap((evaluation) => {
const state = this.get();
return this.requestApproval.patch(state.id, state.companyName, evaluation.id, evaluation.isApproved).pipe(
tapResponse(
(result) => {
// is it better to call patchState()?
this.patchState((state) => {
for(let i = 0; i < state.requestApprovals.length; i++) {
if(state.requestApprovals[i].id == result.id) {
state.requestApprovals[i].isApproved = result.isApproved;
}
}
// the take away is you must assign a whole new array object when you update it.
state.requestApprovals = Object.assign([], state.requestApprovals);
return state;
});
// or this updater?
// this.applyDecisionPatch(evaluation);
},
// oh look! another updater reassigning my array to the state so
// it propagates to subscribers to reset the UI
() => { this.reverseDecision(); }
)
);
})
);
});
// this is private to make sure this can only be called after a network request
private readonly applyDecisionPatch = this.updater((state, value: {id: string, isApproved: boolean}) => {
for(let i = 0; i < state.requestApprovals.length; i++) {
if(state.requestApprovals[i].id == value.id) {
state.requestApprovals[i].isApproved = value.isApproved;
}
}
state.requestApprovals = Object.assign([], state.requestApprovals);
return state;
});
Note: There's no tag for ngrx-component-store so couldn't tag it.
An updater can be compared to a reducer.
All the options to modify the state should change it in an immutable way.
A library like ngrx-immer can be used to make this easier.
The main difference is that updater receives the current state, and you can change the state based on it. E.g. a conditional update, or can be used with #ngrx/entity
While with setState and patchState, you just set state properties.
setState updates the whole state object, whereas patchState only sets the given properties and doesn't touch the rest of the state object.
These two methods are also easier to use when you just want to set the state, because you don't have to create an updater function.
To answer the side question, push is not immutable. Instead of creating a new instance, it updates the array instance.
my code looks like below:
exports.XXX = functions.database.ref("/global/tokenEarned")
.onUpdate(async (change, context) => {
let newValue = change.after.val();
const oldValue = change.before.val()
if(oldValue !== newValue){
const diff = newValue - oldValue
const resp = await db.ref("/global").once("value")
const respData = resp.val()
await db.ref("global").update({"totalDivi" : respData.totalDivi + divi})
}
return null
})
As you can see that i am updating the attribute "totalDivi" whenever another attribute "tokenEarned" gets updated with the difference between new and old value.
this works as expected. However, how this will work in a situation when multiple people are updating the value of tokenEarned? will firebase queue the above function calls in the order value gets updated by multiple users?
Will firebase queue the above function calls in the order value gets
updated by multiple users?
No, there is no guarantee that the executions will follow any ordering, like ordering of triggering of events. The Cloud Function could even be executed simultaneously, in parallel’ if several server instances are spun up.
Depending on your exact use case you may need to go for another solution.
My use case comprises of dispatching two actions from a recursive function (if else construct ) the if part which adds a row in an array ( which is a state of my app) and the else part adds another row and needs to access the length of the array before and call the function itself. What I see here is the length of the array remains same after the first action is being dispatched and thus the call to itself doesn't get the actual value of the length .
My assumption is you are trying to do the second check/call after the first within the component. The component must wait for the new props on the next render. You should move your logic into your action. This is just a guess without more details to the question. Here is an example:
const myAction = (stuff) => {
return (dispatch, getState) => {
let oldLength = getState().myState.stuff.length
dispatch(doStuffToStuff(stuff))
let newLength = getState().myState.stuff.length
dispatch(moreStuffToLength(newLength))
}
}
Thanks the issue was resolved .After every dispatch if the state changes it is required to access the new state by ysing getState() I wasn't doing that .
I have a collection of requests in POSTMAN. I wanted to add a pause between 2 requests but I couldn't find a way to do so from reading their docs. Any idea?
UPDATE I only wanted to put a pause after one request instead of after every request in the collection.
In case someone is still looking for this - You can add delay after/before 1 of many test in a collection you can use:
setTimeout(function(){}, [number]);
where 'number' is the milliseconds. If it's added at 'Tests' it will be executed after request is send. If it's added at Pre-request Scripts it will be executed before request is send.
Using javascript's busy wait is a good hack but it makes your CPU hot and the app unresponsive. I figured out this solution using postman-echo.
Assuming you want to add a long delay between Request_A and Request_B.
First, in Request_A's test script set up an env var to mark the start.
environment.delayTimerStart = new Date();
Then, create a GET request in the creation (here called 'Delay 10s'). It makes a GET on https://postman-echo.com/delay/10 (It returns after 10s)
In its test script, add
var curDate = new Date();
if (curDate - environment.delayTimerStart < delay_time_in_sec*1000) {
postman.setNextRequest('Delay 10s');
} else {
postman.setNextRequest("Request_B");
}
In this way you can add a delay of any length.
Note: 10 sec is the maxium value that postman-echo accepts. If you just need a short delay, simply GET https://postman-echo.com/delay/[1~10].
Try something like this-
if(jsonBody.responseCode=="SUCCESS"){
setTimeout(function(){
console.log("Sleeping for 3 seconds before next request.");
}, 3000);
postman.setNextRequest("nextAPI");
}
I know two possible ways to do this
Method I
Run your request as a collection. (https://www.getpostman.com/docs/collections)
Use Newman (Postman's collection runner from command line) to run your collection with --delay flag. The delay input value is in milliseconds.
Method II
This is a nice hack which I found here https://github.com/postmanlabs/postman-app-support/issues/1038. You can add a delay function to your test script in Postman.
Just simple example, I'm sure you will be understand.
setTimeout(() => {}, 15000);
15000 it's a value in miliseconds
looking at the current documentation if you are using Postman Runner
Delay
This is the interval (in ms) between each request in your collection run.
https://www.getpostman.com/docs/postman/collection_runs/starting_a_collection_run
and if you are using newman
--delay-request [number] Specify a delay (in ms) between requests [number]
https://www.getpostman.com/docs/postman/collection_runs/command_line_integration_with_newman
If you have the standalone Postman App (supports ES7) and you are intending to test only on Postman, not on newman(which doesn't support ES7), then you can have something like this in the Pre-Request script of the Request you want to delay:
function foo() {
return (new Promise((resolve, reject) => {
setTimeout(() => {
resolve("done!"); // passing argument is optional, can just use resolve()
}, 10000) // specify the delay time in ms here..
}))
}
async function waitForMe() {
await foo().then((val) => {
console.log(val); // not required, you can just do an await without then
})
}
waitForMe();
I prefer to use an online service Postman Echo's delay endpoint (docs are here). Simply create a request that uses this service and call it between the two other requests you wish to add a delay between.
If you want to check the status of something before continuing, you can use postman.setNextRequest() in the Tests of a request to loop until something has been completed. Simply do the following:
1) Create a collection structured as:
Delay For 10 Seconds
Status Check
Continue Processing
2) In the Status Check request Tests:
if(responseBody.has("Success")) //or any other success condition
{
postman.setNextRequest('Continue Processing');
tests["Success found"] = true;
}
else
{
postman.setNextRequest('Delay For 10 Seconds');
tests["No success found"] = true;
}
You can use JavaScript setTimeout method. This will make sure that your method will be executed after given delay.
setTimeout(checkStatusCode, 500);
function checkStatusCode() {
pm.sendRequest('https://postman-echo.com/get', function (err, res) {
tests['status code should be 200']= res.code ===200;
});
}
Is it possible yet, to preserve insertion order or set reliable timestamps in Meteor given that MongoDB doesn't guarantee to return items in insertion order if no sort is specified, a document's _id is randomly generated and setting a timestamp manually on insertion would depend upon the client's clock?
I suggest a method.
Meteor.methods({
addItem: function (doc) {
doc.when = new Date;
return Items.insert(doc);
}
});
While the client will run this locally and set when to its own current time, the server's timestamp takes priority and propagates to all subscribed clients, including the original client. You can sort on doc.when.
We'll probably add hooks for setting timestamps automatically as part of document validations and permissions.
If you're willing to use something like these collection hooks (https://gist.github.com/matb33/5258260), along with this fancy Date.unow function (which you can safely sort on even if many documents were inserted with the same timestamp):
if (!Date.unow) {
(function () {
var uniq = 0;
Date.unow = function () {
uniq++;
return Date.now() + (uniq % 5000);
};
})();
}
if (Meteor.isServer) {
// NOTE: this isn't vanilla Meteor, and sometime in the future there may be
// a better way of doing this, but at the time of writing this is it:
Items.before("insert", function (userId, doc) {
doc.created = Date.unow();
});
}