Stream: helpdesk (published)

Topic: Rocket.jl: how to consume/produce different types


view this post on Zulip G Gundam (Dec 08 2024 at 23:36):

How do I tell Rocket.jl that I want to create a subject that consumes one type and produces another?

Back Story

What the following code is trying to do

image.png

Simple.

The Code

Notice the AbstractSubject{Any}. I would like to be more specific if possible.

using Rocket

@kwdef mutable struct IntToFloat64Subject <: AbstractSubject{Any}
    subscribers::Vector
end

function Rocket.on_subscribe!(subject::IntToFloat64Subject, actor)
    push!(subject.subscribers, actor)
    return voidTeardown
end

function Rocket.on_complete!(subject::IntToFloat64Subject)
    println("IntToFloat64Subject Completed!")
end

function Rocket.on_next!(subject::IntToFloat64Subject, i::Int)
    # consume Int
    f = convert(Float64, i)
    for sub in subject.subscribers
        # produce Float64
        next!(sub, f)
    end
end

@kwdef mutable struct Float64ToStringSubject <: AbstractSubject{Any}
    subscribers::Vector
end

function Rocket.on_subscribe!(subject::Float64ToStringSubject, actor)
    push!(subject.subscribers, actor)
    return voidTeardown
end

function Rocket.on_complete!(subject::Float64ToStringSubject)
    println("FloatToStringSubject Completed!")
end

function Rocket.on_next!(subject::Float64ToStringSubject, f::Float64)
    s = "> " * string(f)
    for sub in subject.subscribers
        # produce Float64
        next!(sub, s)
    end
end

# Setting up the data flow backwards
fts_subject = Float64ToStringSubject([])
subscribe!(fts_subject, logger("final"))

itf_subject = IntToFloat64Subject([])
subscribe!(itf_subject, fts_subject)

ints = from(collect(1:5))
subscribe!(ints, itf_subject) # This starts the data flow.

Output

[final] Data: > 1.0
[final] Data: > 2.0
[final] Data: > 3.0
[final] Data: > 4.0
[final] Data: > 5.0
IntToFloat64Subject Completed!
VoidTeardown()

Is there any way around saying AbstractSubject{Any}?


Last updated: Dec 28 2024 at 04:38 UTC