Home > database >  use socket.io client in dart in different places with a single instance
use socket.io client in dart in different places with a single instance

Time:04-11

I use Bloc and repositories, I'm going to use the socket in different places in the project. each api package has its own events but shares the same socket. I want to connect once and use it in multiple places and packages. Is that possible?

// use socket in multiple files 
final socket = SocketApi().init();

In javascript I would export { socket }

package : https://pub.dev/packages/socket_io_client

CodePudding user response:

To achieve your required functionality you will need to create one class for Socket IO plugin which will do all the interections with SocketIO package's code and also you will need to create one factory constructor so use same SocketApi object across the application.

Example of factory constructor.

class SocketApi {
        // A static private instance to access _socketApi from inside class only
        static final SocketApi _socketApi = SocketApi._internal();

        // An internal private constructor to access it for only once for static instance of class.
        SocketApi._internal();

        // Factry constructor to retutn same static instance everytime you create any object.        
        factory SocketApi() {
            return _socketApi;
        }

        // All socket related functions.
    
    }

Usage

SocketApi socketApi = SocketApi();

You can learn more about factory constructor here.

CodePudding user response:

Yes, Of course, that is possible. You can make one singleton service and access it on a global level. When you need to ensure only a single instance of a class is created, and you want to provide a global point of access to it, the Singleton design pattern can be of great help.

class SocketSingleton {
  Socket _socket;

  SocketSingleton._privateConstructor();

  static final SocketSingleton _instance = 
  SocketSingleton._privateConstructor();

  static SocketSingleton get instance => _instance;
  static SocketSingleton get socket => _socket;
   
  initSocket() {
       _socket = SocketApi().init();
  }
}
  • Related