examples: improve the sendbus example (#13604)

pull/13609/head
Mihai Galos 2022-02-26 08:50:44 +01:00 committed by GitHub
parent 0d9792bdf2
commit 4215bb125c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 15 deletions

View File

@ -2,12 +2,32 @@ module main
import some_module import some_module
fn main() { struct Receiver {
mut sub := some_module.get_subscriber() mut:
sub.subscribe('error', on_error) ok bool
some_module.do_work()
} }
fn on_error(sender voidptr, e &some_module.MyError, x voidptr) { fn main() {
println(e.message) mut sub := some_module.get_subscriber()
r := Receiver{}
sub.subscribe_method('event_foo', on_foo, r)
sub.subscribe('event_bar', on_bar)
sub.subscribe('event_baz', on_baz)
println('Receiver ok: ' + r.ok.str())
some_module.do_work()
println('Receiver ok: ' + r.ok.str())
}
fn on_foo(mut receiver Receiver, e &some_module.EventMetadata, sender voidptr) {
receiver.ok = true
println('on_foo :: ' + e.message)
}
fn on_bar(receiver voidptr, e &some_module.EventMetadata, sender voidptr) {
println('on_bar :: ' + e.message)
}
fn on_baz(receiver voidptr, event voidptr, d &some_module.Duration) {
println('on_baz :: ' + d.hours.str())
} }

View File

@ -6,27 +6,27 @@ const (
eb = eventbus.new() eb = eventbus.new()
) )
pub struct Work { pub struct Duration {
pub: pub:
hours int hours int
} }
pub struct MyError { pub struct EventMetadata {
pub: pub:
message string message string
} }
pub fn do_work() { pub fn do_work() {
work := Work{20} duration := Duration{10}
for i in 0 .. 20 { for i in 0 .. 10 {
println('working...') println('working...')
if i == 15 { if i == 5 {
error := &MyError{'There was an error.'} event_metadata := &EventMetadata{'Iteration ' + i.str()}
some_module.eb.publish('error', work, error) some_module.eb.publish('event_foo', duration, event_metadata)
some_module.eb.publish('error', work, error) some_module.eb.publish('event_bar', duration, event_metadata)
return
} }
} }
some_module.eb.publish('event_baz', &Duration{42}, &EventMetadata{'Additional data at the end.'})
} }
pub fn get_subscriber() eventbus.Subscriber { pub fn get_subscriber() eventbus.Subscriber {