Skip to content

Singleton services #4

@woubuc

Description

@woubuc

Is your feature request related to a problem? Please describe.
I have a service that manages the configuration data for my application. This configuration data is loaded from a file when the service is created, and is saved whenever a value is changed. These changes can be sent to the service from any other service/actor, but only one instance of the ConfigService should ever exist because it holds a handle to the config file and multiple instances would override each others' changes and potentially lose config data.

I've used ServiceConcurrency::None to have only a single instance of the service, but it still requires that the data is wrapped in a Mutex. It's possible to make a singleton this way, but not very convenient/user-friendly for something where I should be able to assume concurrent access will not happen (because messages are processed one by one).

Describe the solution you'd like
A Singleton trait, similar to Service, that guarantees only a single instance of the service exists, that doesn't require me to use a Mutex for its state, and that uses &mut self for its Listen & Serve traits.

Example (pseudocode):

struct ConfigService {
    file_handle: File,
}

impl Singleton for ConfigService {
    async fn initialize(system) -> Self {
        ConfigService {
            file: File::Open().await,
        }
    }
}

struct SetConfig(String);

impl Listen<SetConfig> for ConfigService {
    async fn handle(&mut self, data: SetConfig) {
        self.file.write_all(data.0).await;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions