Swiftpack.co - givtnl/Mediater.Swift as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
givtnl/Mediater.Swift
This is the repository where Givt develops its implementation of the Mediater pattern in Swift language
.package(url: "https://github.com/givtnl/Mediater.Swift.git", from: "0.9.0")

Mediater.Swift

This a Swift implementation of the Mediater pattern inspired by https://github.com/jbogard/MediatR

Example usage with SwiftUI

// SwiftMediaterExample.swift
@main
struct SwiftMediaterExample: App {
	var body: some Scene {
		...
	}
	init() {
		registerHandlers()
	}
	func registerHandlers() {
		Mediater.shared.registerHandler(GetAllPlayersQuery())
	}
}

Here is how we define a query

// GetAllPlayersQuery.swift
import MediaterSwift

class GetAllPlayersQuery: RequestProtocol {
	typealias TResponse = Array<Player>
}

Here is how we define the handler which in turn executes the query and returns the result

// GetAllPlayersQueryHandler.swift
import MediaterSwift
import CoreData

class GetAllPlayersQueryHandler: RequestHandlerProtocol {
	let coreDataContext: CoreDataContext.shared
	
	func handle<R>(request: R, completion: @escaping (R.TResponse) throws -> Void) throws where R : RequestProtocol {
		var result: Array<Player> = []
		
		let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Player")
		let fetchRequestResult = try coreDataContext.container.viewContext.fetch(fetchRequest)
		
		for fetchResult in fetchRequestResults {
			let player = Player(
				fetchResult.value(forKey: "id") as! UUID,
				fetchResult.value(forKey: "name") as! String,
				fetchResult.value(forKey: "isPlaying") as! Bool
			)
			result.append(player)
		}
		try completion(result as! R.TResponse)
	}	
	
	func canHandle<R>(request: R) -> Bool where R: RequestProtocol  {
		request is GetAllPlayersQuery
	}
}

Now simply get the result from the query like this from anywhere in your code

var players = Mediater.shared.send(GetAllPlayersQuery())

GitHub

link
Stars: 0
Last commit: 4 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics