Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native: Always running component

I don't know actually, how to name this question!

I've a JS file in react native that fetches data from server and compares it to local database. i need this to run simultaneously, how can i achieve that? when app starts, that should run, changing views (navigation to other components) should not destroy it, it should still be running.

Any solutions?

like image 722
Ata Mohammadi Avatar asked Sep 28 '16 07:09

Ata Mohammadi


People also ask

Is it possible to run a React Native app in the background?

With the use of endless task management system in android You can run the task in the background theater the app is in background or the app is in kill mode.

What is Headlessjs in React Native?

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

Is React Native 60 fps?

The views in React Navigation use native components and the Animated library to deliver 60 FPS animations that are run on the native thread.


1 Answers

You are explaining a design pattern of something called: Singleton.

Here's how to do it:

let instance = null;

class Singleton{  
    constructor() {
        if(!instance){
              instance = this;
        }

        // to test whether we have singleton or not
        this.time = new Date()

        return instance;
      }
}

Testing singleton On above class we have defined a time property to make sure we have singleton working properly.

 let singleton = new Singleton()
 console.log(singleton.time);

 setTimeout(function(){
   let singleton = new Singleton();
   console.log(singleton.time);
 },4000);

If it prints the same time for both the instances, it means we have a working singleton.

Now, you can load your server data asynchronously inside the singleton and do whatever you'd like to do with it. Anytime you try to access the singleton class, it will be the same instance and it will not be instantiated more than once. In other words, it will not be destroyed.

Source: http://amanvirk.me/singleton-classes-in-es6/

like image 90
Ahmad Al Haddad Avatar answered Oct 03 '22 15:10

Ahmad Al Haddad