Amplify DataStore: How to know when sync is finished? - flutter

How can we know that DataStore has finished the sync?
When doing the first await DataStore.query(MyEntity) after the user logged in, DataStore is returning right away and not waiting for the data to be synced with the cloud.
I want to wait for the sync to be completed and put a loading when the data isn't synced yet.

make your model class observable so that it can check for data in realtime
Amplify.DataStore.observeQuery(MyEntity.classType).listen((event) {
if (event.isSynced) {//boolean value
print("Synced Successfully!");
// even you can get synced data here also
List< MyEntity> items = event.items;
} else {
//Show ProgressBar Here
print("Fetching Data From Cloud");
}
});

You can listen to events on the datastore channel with Amplify.Hub.listen.
details:
subscription = Amplify.Hub.listen([HubChannel.DataStore], (dynamic hubEvent) async {
switch (hubEvent.eventName) {
case 'networkStatus':
_amplifyIsUp.value = hubEvent.payload.active;
break;
case 'subscriptionsEstablished':
_amplifyMessage.value = 'Starting to sync from cloud...';
break;
case 'syncQueriesStarted':
_amplifyIsSyncing.value = true;
_amplifyMessage.value = 'Syncing...';
break;
case 'modelSynced':
ModelSyncedEvent mse = hubEvent.payload;
_amplifyMessage.value = '${mse.modelName} has been sync\'d from cloud...';
break;
case 'syncQueriesReady':
_amplifyMessage.value = 'Done!';
_amplifyIsSyncing.value = false;
///do your bits here
onSyncsReady.call();
break;
case 'ready':
_amplifyIsSyncing.value = false;
break;
case 'subscriptionDataProcessed':
SubscriptionDataProcessedEvent sdpe = hubEvent.payload;
_amplifyMessage.value = 'Syncing ${sdpe.element.model.classType.modelName()}...';
if (sdpe.element.model is DeviceStatus) {
DeviceStatus ds = sdpe.element.model as DeviceStatus;
if (ds.clientID == _clientService.client.id && ds.status == Status.REQUESTSTATUS) {
_statusService.performHeartbeat();
}
}
break;
case 'outboxMutationEnqueued':
_amplifyIsSyncing.value = true;
_amplifyHasDirt.value = true;
break;
case 'outboxMutationProcessed':
OutboxMutationEvent ome = hubEvent.payload;
_amplifyIsSyncing.value = false;
break;
case 'outboxStatus':
OutboxStatusEvent ose = hubEvent.payload;
if (ose.isEmpty) {
_amplifyIsSyncing.value = false;
_amplifyHasDirt.value = false;
} else {
_amplifyHasDirt.value = true;
}
break;
}
});
boop

Related

Geofire query at location

I'm building an app which uses location. The people who are closer to 10 meters should be showed.
I use Geofire but the problem I'm facing is the value I pass to it's radius for it to get me people doesn't work at all. I pass 10 meters but when I calculate the distance using distance between, of the list of people it gave me I get 346 meters instead. Is it a problem from their end or mine? That is my code.
Geofire.queryAtLocation(position.latitude, position.longitude, chat)!.listen((map) {
print("This is the map: $map");
if (map != null) {
var callBack = map['callBack'];
double value = Geolocator.distanceBetween(position.latitude, position.longitude,
map['latitude'], map['longitude']);
print("Distance: $value meters");
switch (callBack) {
case Geofire.onKeyEntered:
NearByUsers nearbyUsers = NearByUsers();
nearbyUsers.key = map['key'];
nearbyUsers.latitude = map['latitude'];
nearbyUsers.longitude = map['longitude'];
if(value < chat) {
GeofireAssistant.nearbyAvailableUsers.add(nearbyUsers);
if (nearbyAvailableUserKeysLoaded == true) {
RequestAssistant.updateUsers();
}
}
break;
case Geofire.onKeyExited:
GeofireAssistant.removeDriveFromList(map['key']);
RequestAssistant.updateUsers();
break;
case Geofire.onKeyMoved:
NearByUsers nearbyUsers = NearByUsers();
nearbyUsers.key = map['keys'];
nearbyUsers.latitude = map['latitude'];
nearbyUsers.longitude = map['longitude'];
GeofireAssistant.nearbyAvailableUsers.add(nearbyUsers);
GeofireAssistant.updateNearbyLocation(nearbyUsers);
RequestAssistant.updateUsers();
break;
case Geofire.onGeoQueryReady:
RequestAssistant.updateUsers();
break;
}
}
if (mounted) {
setState(() {
// Your state change code goes here
});
}
});```

Unable to catch Google cloud storage exception

I have a function in my flutter app to download a file from google cloud and store it locally. This function works for existing files, but when I try to download a non existent file, it fails to catch the 'file not found' exception. I'm obviously doing something wrong, but I can't figure it out!
bool downloadFile({required String localFile, required String remoteFile}) {
try {
final storageRef = FirebaseStorage.instance.ref();
final remoteFileRef = storageRef.child(remoteFile);
final file = File(localFile);
final downloadTask = remoteFileRef.writeToFile(file);
downloadTask.snapshotEvents.listen((taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
print('TaskState.running');
break;
case TaskState.paused:
print('TaskState.paused');
break;
case TaskState.success:
print('TaskState.success');
break;
case TaskState.canceled:
print('TaskState.canceled');
break;
case TaskState.error:
print('TaskState.error');
break;
}
});
//} on firebase_core.FirebaseException catch (error) {
} catch (e) {
print("########### got ex");
return false;
}
return true;
}

How can you setup a flutter rawkeyboardlistener to read {} (curly brackets) instead of square brackets?

I have a flutter solution that interprets a QR code via a scanning device. I use the RawKeyboardListener to read the scanned QR code that then parses it into a variable.
The QR value is an object {something: somethingelse}, but when read by the RawKeyboardListener, it reads the {} as [] and as a result, the object is then invalid.
String runtime = event.runtimeType.toString();
if (event.data.logicalKey != LogicalKeyboardKey.enter) {
setState(() {
scannedItem += runtime == 'RawKeyUpEvent' ? event.data.keyLabel : '';
});
} else if (scannedItem != '') {
setState(() {
var data = json.decode(scannedItem);
});
}
I played around with the solution and ended up fixing it, though I do feel there is a better way of resolving this
if (event.data.isShiftPressed) {
switch (event.data.logicalKey.debugName) {
case 'Bracket Left':
keyLabel = '{';
break;
case 'Bracket Right':
keyLabel = '}';
break;
case 'Quote':
keyLabel = '"';
break;
case 'Semicolon':
keyLabel = ':';
break;
default:
keyLabel = keyLabel.toUpperCase();
break;
}
}

Cancel Or Exit from PromptDialog.Choice Flow in Microsoft Bot Framework

i have a Prompt with 4 options, the last option is user can quit the Prompt,
i want to implement some code so that the bot exit the Prompt
Image
PromptDialog.Choice(context, this.OnOptionSelected, new List<string>() { FlightsOption, HotelsOption, TrainOption, GobackOption }, "Sure..! Tell me what booking would like to make..?", "Not a valid option", 3);
in above image i had implemented quit option on which if user selects quit it goes to Switch case of quit.
i had also tried context.quit but it throws error
private async Task OnOptionSelected(IDialogContext context, IAwaitable<string> result)
{
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
//want some code here to quit the form
break;
}
}
First of all this is not a Form Flow. This is prompt.
Now You can do something like, either you exit the dialog from the stack like this
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
context.Done<object>(null);
break;
}
}
Or,
You can tell something and then wait for other message in the same dialog like this
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
await context.PostAsync("Ok, you came back. Now tell something new.");
context.Wait(MessageReceivedAsync);
break;
}
}
And the next message will go here
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
context.Wait(MessageReceivedAsync);
}

Any other option to deploy in jboss server ither than hot deployment?

I want to know what are the methods to deploy in jboss server other than hot deployment.
Get the client and the builder to build plans:
ModelControllerClient client = ModelControllerClient.Factory.create(host, port);
ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client);
DeploymentPlanBuilder builder = manager.newDeploymentPlan();
And the method to execute any kind of operation (here some ones are implemented):
public DeployementActionStatus execute(Type deploy) throws IOException
{
List<Throwable> errors = new LinkedList<Throwable>();
DeployementActionStatus status = DeployementActionStatus.SUCCESS;
switch (deploy)
{
case DEPLOY:
if (archive != null)
{
plan = builder.add(archive).deploy(archive.getName()).build();
}
else
{
return DeployementActionStatus.FAILURE;
}
break;
case REDEPLOY:
{
if (archive != null)
{
plan = builder.redeploy(archive.getName()).build();
}
else
{
return DeployementActionStatus.FAILURE;
}
break;
}
case UNDEPLOY:
{
plan = builder.undeploy(getApplicationName()).build();
break;
}
case REMOVE:
{
plan = builder.remove(getApplicationName()).build();
break;
}
default:
plan = null;
break;
}
if (plan == null)
{
throw new IllegalStateException("Invalid type: " + deploy);
}
if (plan.getDeploymentActions().size() > 0)
{
try
{
final ServerDeploymentPlanResult planResult = manager.execute(plan).get();
// Check the results
for (DeploymentAction action : plan.getDeploymentActions())
{
final ServerDeploymentActionResult actionResult = planResult.getDeploymentActionResult(action
.getId());
final ServerUpdateActionResult.Result result = actionResult.getResult();
switch (result)
{
case FAILED:
case NOT_EXECUTED:
case ROLLED_BACK:
{
log.error(actionResult.getDeploymentException());
if (actionResult.getDeploymentException().getMessage() != null
&& actionResult.getDeploymentException().getMessage().contains("Duplicate"))
{
status = DeployementActionStatus.FAILURE_ALREADY_DEPLOYED;
}
else
{
status = DeployementActionStatus.FAILURE;
}
break;
}
case CONFIGURATION_MODIFIED_REQUIRES_RESTART:
// Should show warning
break;
default:
break;
}
}
}
catch (InterruptedException e)
{
errors.add(e);
status = DeployementActionStatus.FAILURE;
}
catch (ExecutionException e)
{
errors.add(e);
status = DeployementActionStatus.FAILURE;
}
catch (Exception e)
{
if (e instanceof RuntimeException)
{
status = DeployementActionStatus.CONNECTION_TO_SERVER_FAILED;
}
}
}
return status;
}
Deploying is considered hot only when JBoss is running. If you don't want hot deployment you can turn off deployment scanner [1] or stop JBoss and deploy the artifact.
[1] https://community.jboss.org/wiki/ConfiguringTheDeploymentScannerInConfjbossSystemxml