Skip to main content
Version: 7.0.1

AsyncTask

API Reference: AsyncTask

AsyncTask can be used in cases where UI thread can cause performance issues. AsyncTask creates a different thread to overcome this.

Use Cases
  • Downloading large files
  • Accessing DB
  • Parsing JSON
  • And other heavy operations such as searching in large text
danger

AsyncTask is used for non UI operations. Any UI operation performed in task method will result in unexpected errors.

In the following example, assume we have performed a request that will response with large data. That large data is parsed using AsyncTask.

TypeScript
import PageSampleDesign from "generated/pages/page3";
import { Route, Router } from "@smartface/router";
import Application from "@smartface/native/application";
import Http from "@smartface/native/net/http";
import Blob from "@smartface/native/global/blob";
import AsyncTask from "@smartface/native/asynctask";


//You should create new Page from UI-Editor and extend with it.
export default class Sample extends PageSampleDesign {
http: Http = new Http();

constructor(private router?: Router, private route?: Route) {
super({});
}

// The page design has been made from the code for better
// showcase purposes. As a best practice, remove this and
// use WYSIWYG editor to style your pages.
centerizeTheChildrenLayout() {
this.dispatch({
type: "updateUserStyle",
userStyle: {
flexProps: {
flexDirection: 'ROW',
justifyContent: 'CENTER',
alignItems: 'CENTER'
}
}
})
}

onShow() {
super.onShow();
const { headerBar } = this;
Application.statusBar.visible = false;
headerBar.visible = false;

}

onLoad() {
super.onLoad();
this.centerizeTheChildrenLayout();

this.http.request({
url: "https://api.github.com/repos/smartface/contxjs",
method: "GET",
onLoad: (response: {
statusCode: number;
headers: { [key: string]: string };
body: Blob;
}): void => {
let result = response.body.toString();
let parsedObject;
// Run new task
var asyncTask = new AsyncTask();
asyncTask.task = function () {
parsedObject = JSON.parse(result);
};
asyncTask.onComplete = function () {
console.log("parsedObject ", parsedObject);
};
asyncTask.run();
},
onError: (e: {
message: string;
body: any;
statusCode: number;
headers: { [key: string]: string };
}): void => {
// Handle error
},
});
}
}