typed-notifications

0.0.8

A library attaching type-information to NotificationCenter
mtj0928/typed-notifications

What's New

0.0.8 (Update a package)

2024-03-17T15:11:52Z

typed-notifications

This library attaches type-information to NotificationCenter. You can post and observe notifications in a type-safe manner.

TypedNotificationCenter.default
    .publisher(for: .userNameUpdate, object: user)
    .sink { notification in
        // Notifications can be received in a type safe manner.
        let storage: UserNameUpdateNotificationStorage = notification.storage
        let user: User? = notification.object
        // ...
    }

extension TypedNotificationDefinition {
    @Notification
    static var userNameUpdate: TypedNotificationDefinition<UserNameUpdateNotificationStorage, User> 
}

@UserInfoRepresentable
struct UserNameUpdateNotificationStorage {
    let oldName: String
    let newName: String
}

How to Use

Define a notification and how to encode/decode the userInfo in TypedNotificationDefinition.

extension TypedNotificationDefinition {
    static var userNameWillUpdate: TypedNotificationDefinition<String, User> {
        .init(name: "userWillUpdate") { newName in
            ["newName": newName]
        } decode: { userInfo in
            userInfo?["newName"] as? String ?? ""
        }
    }
}

And then, you can post/observe the notifications in type safe manner.

// [Post]
// Notifications can be posted in a type safe manner.
let newName: String = ...
let user: User = ...
TypedNotificationCenter.default.post(.userNameWillUpdate, storage: newName, object: user)

// [Observation]
TypedNotificationCenter.default.publisher(for: .userNameWillUpdate, object: user)
    .sink { notification in
        // Notifications can be received in a type safe manner.
        let newName = notification.storage
        let user: User? = notification.object
        // ...
    }

Notification macro

You can use @Notification macro, if @UserInforRepresentable macro is attached to your type.

extension TypedNotificationDefinition {
    @Notification
    static var userNameUpdate: TypedNotificationDefinition<UserNameUpdateNotificationStorage, User> 
}

@UserInfoRepresentable
struct UserNameUpdateNotificationStorage {
    let oldName: String
    let newName: String
}

Pre-defined Notifications

This repository contains frequent system notifications.

Your PR adding new notifications is appreciated. Feel free to make a new PR.

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

Last updated: Fri Apr 12 2024 02:30:39 GMT-0900 (Hawaii-Aleutian Daylight Time)