mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
examples: improve the sendbus example (#13604)
This commit is contained in:
parent
0d9792bdf2
commit
4215bb125c
@ -2,12 +2,32 @@ module main
|
||||
|
||||
import some_module
|
||||
|
||||
fn main() {
|
||||
mut sub := some_module.get_subscriber()
|
||||
sub.subscribe('error', on_error)
|
||||
some_module.do_work()
|
||||
struct Receiver {
|
||||
mut:
|
||||
ok bool
|
||||
}
|
||||
|
||||
fn on_error(sender voidptr, e &some_module.MyError, x voidptr) {
|
||||
println(e.message)
|
||||
fn main() {
|
||||
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())
|
||||
}
|
||||
|
@ -6,27 +6,27 @@ const (
|
||||
eb = eventbus.new()
|
||||
)
|
||||
|
||||
pub struct Work {
|
||||
pub struct Duration {
|
||||
pub:
|
||||
hours int
|
||||
}
|
||||
|
||||
pub struct MyError {
|
||||
pub struct EventMetadata {
|
||||
pub:
|
||||
message string
|
||||
}
|
||||
|
||||
pub fn do_work() {
|
||||
work := Work{20}
|
||||
for i in 0 .. 20 {
|
||||
duration := Duration{10}
|
||||
for i in 0 .. 10 {
|
||||
println('working...')
|
||||
if i == 15 {
|
||||
error := &MyError{'There was an error.'}
|
||||
some_module.eb.publish('error', work, error)
|
||||
some_module.eb.publish('error', work, error)
|
||||
return
|
||||
if i == 5 {
|
||||
event_metadata := &EventMetadata{'Iteration ' + i.str()}
|
||||
some_module.eb.publish('event_foo', duration, event_metadata)
|
||||
some_module.eb.publish('event_bar', duration, event_metadata)
|
||||
}
|
||||
}
|
||||
some_module.eb.publish('event_baz', &Duration{42}, &EventMetadata{'Additional data at the end.'})
|
||||
}
|
||||
|
||||
pub fn get_subscriber() eventbus.Subscriber {
|
||||
|
Loading…
Reference in New Issue
Block a user