Issue
i am fetching data from webservice using HttpClient
and storing it into Realm
database. My screen automatically starts the fetching data and showing ActivityIndicator
till data gets loaded and stored in database.
Now the issue is , i have lot of data to be deserialized using JsonConvert.DeserializeObject<Response>(content)
as the data is huge this statement blocks/freezes my ActivityIndicator
on UI screen.
how i can i deserialize object in background thread so that it doesn't block UI.
here is my code
var response = await Service.createService<HttpResponseMessage>("HTTP").sendData(url, jsonData);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Response responseData = JsonConvert.DeserializeObject<Response>(content);
DB.createDB<EventType>("realm").subscribe();
if (responseData != null)
{
// status is ok
if (responseData.status.ToUpper() == OK)
{
MessagingCenter.Send<IMessage, EventType>(this, DB_EVENT, new EventTypeBuilder().status(true).requestType(url).response(responseData).Build());
}// status is error
else if (responseData.status.ToUpper() == ERROR)
{
MessagingCenter.Send<IMessage, EventType>(this, UI_EVENT, new EventTypeBuilder().status(false).requestType(url).errorMessage(responseData.errorMessage).Build());
}
}
else // when response is null
MessagingCenter.Send<IMessage, EventType>(this, UI_EVENT, new EventTypeBuilder().status(false).requestType(url).errorMessage(ERROR_RESPONSE_NULL).Build());
}
else
{ // when some error occured
response.EnsureSuccessStatusCode();
}
Response responseData = JsonConvert.DeserializeObject<Response>(content);
blocks my thread
Solution
You can run it on its own thread and await the results:
Response responseData;
await Task.Run(() =>
{
responseData = JsonConvert.DeserializeObject<Response>(content);
// preform your Realm database add/updates,
// remember you are now on a different thread so get a new Realm Instance
});
Queues the specified work to run on the thread pool and returns a Task object that represents that work.
Answered By - SushiHangover
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.