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
|
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())
|
||||||
}
|
}
|
||||||
|
@ -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 {
|
||||||
|
Loading…
Reference in New Issue
Block a user