ios – What’s a scalable, testable and SOLID adhering sample for injecting a shared service between grandparent and baby view, in SwiftUI?

0
14
ios – What’s a scalable, testable and SOLID adhering sample for injecting a shared service between grandparent and baby view, in SwiftUI?


I’m utilizing Mvvm structure, DI and protocols. Suppose you’ve three views Grandparent, Mother or father and Baby. GrandparentView will depend on ServiceA , ParentView will depend on ServiceB and baby view will depend on serviceA. GrandParentView and ChildView rely on the shared occasion of ServiceA.

GrandparentView -> ParentView -> ChildView

Protocols for Companies:

protocol ServiceAProtocol {
    func performActionA()
}

protocol ServiceBProtocol {
    func performActionB()
}

Concrete Implementations:

class ServiceA: ServiceAProtocol {
    func performActionA() {
        print("Motion A carried out")
    }
}

class ServiceB: ServiceBProtocol {
    func performActionB() {
        print("Motion B carried out")
    }
}

ViewModels:

@Observable
class GrandparentViewModel {
    personal var serviceA: ServiceAProtocol
    
    init(serviceA: ServiceAProtocol) {
        self.serviceA = serviceA
    }

    func doSomethingWithA() {
        serviceA.performActionA()
    }
}

@Observable
class ParentViewModel {
    personal var serviceB: ServiceBProtocol
    
    init(serviceB: ServiceBProtocol) {
        self.serviceB = serviceB
    }

    func doSomethingWithB() {
        serviceB.performActionB()
    }
}

@Observable
class ChildViewModel {
    personal var serviceA: ServiceAProtocol
    
    init(serviceA: ServiceAProtocol) {
        self.serviceA = serviceA
    }

    func doSomethingWithA() {
        serviceA.performActionA()
    }
}

What needs to be a scalable view implementation or how ought to I construction my code in order that it’s scalable? I don’t wish to move a dependency to a dad or mum view simply to move it to the kid view except the dad or mum additionally will depend on it.

LEAVE A REPLY

Please enter your comment!
Please enter your name here