Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider something like LifecycleWorker #71

Open
bencochran opened this issue Sep 21, 2020 · 1 comment
Open

Consider something like LifecycleWorker #71

bencochran opened this issue Sep 21, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@bencochran
Copy link
Collaborator

Kotlin has LifecycleWorker that makes it easy to perform side-effects when the worker is started or stopped.

At the moment, this is essentially equivalent to doing the following in Swift:

func render(state: State, context: RenderContext<SomeWorkflow>) -> Rendering {
    let onStart: () -> Void = 
    let onEnd: () -> Void = 

    context.runSideEffect(key: "lifecycle") { lifetime in
        onStart()
        lifetime.onEnded(onEnd)
    }

    
}

We might consider making some convenience for this in Swift land. I’d hesitate tying it to Worker specifically since that lives in WorkflowReactiveSwift and this could be built more generally.

Open to suggestions on API shape

@bencochran bencochran added the enhancement New feature or request label Sep 21, 2020
@AquaGeek
Copy link
Collaborator

I think it'd be easier if we tied this to Worker, but we could build it more generally:

public struct LifecycleWorker {
    let key: AnyHashable
    let onStarted: () -> Void
    let onStopped: () -> Void

    init(key: AnyHashable, onStarted: @escaping () -> Void, onStopped: @escaping () -> Void) {
        self.key = key

        self.onStarted = onStarted
        self.onStopped = onStopped
    }
}

extension LifecycleWorker: AnyWorkflowConvertible {
    public typealias Rendering = Void
    public typealias Output = Never

    public func asAnyWorkflow() -> AnyWorkflow<Rendering, Output> {
        LifecycleWorkerWorkflow(worker: self).asAnyWorkflow()
    }
}

// Internal plumbing

struct LifecycleWorkerWorkflow: Workflow {
    typealias State = Void
    typealias Rendering = Void

    private var worker: LifecycleWorker

    init(worker: LifecycleWorker) {
        self.worker = worker
    }

    func render(state: Void, context: RenderContext<LifecycleWorkerWorkflow>) -> Void {
        context.runSideEffect(key: worker.key) { lifetime in
            worker.onStarted()
            lifetime.onEnded(worker.onStopped)
        }
    }
}

Does it create confusion that this is a "worker" but the worker definition lives in the other module?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants