Example

To look at the impact of background threads, we will add another feature to the GoMail application—updating the user interface when a new email arrives. To enable this, we must listen to the Incoming channel that our client.EmailServer type defines.

First, we create a function that will handle incoming email. This is simply a wrapper to a new method, appendEmail(*client.EmailMessage), that handles adding new items to the email list. But it must create a wrapping func() and pass it to ui.QueueMain so that the code executes on the correct thread:

func (m *mainUI) incomingEmail(email *client.EmailMessage) {
ui.QueueMain(func() {
m.appendEmail(email)
})
}

Then we add a little more code to our main() method to listen for incoming emails from client.EmailServer. The following code requests the incoming channel from the server model and then loops over any emails that are communicated through the channel, triggering our handler for any that arrive:

go func() {
incoming := server.Incoming()
for email := range incoming {
main.incomingEmail(email)
}
}()

With these updates running, the same client will trigger a new email to appear after 10 seconds. With Go, the concurrency is simple to handle, and the preceding code shows how andlabs UI allows us to benefit from that in the handling of our user interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.255