Background processing

All user interface code with Walk must run on the main thread; this is a constraint of the winAPI that handles the widgets. This means that any work in the background must change threads before running any UI code. This is done using the Synchronize() function on walk.Window. It takes a single function as a parameter and ensures that the code it contains will be run appropriately.

To handle the updating when an incoming email arrives, we create a new function, incomingEmail(), that will update our email list model. This function will cause an email to be added to the model, which will happen on the main thread so that the user interface can be updated to reflect the new data:

func (g *GoMailUIBrowse) incomingEmail(email *client.EmailMessage, model *EmailClientModel) {
g.window.Synchronize(func() {
model.AddEmail(email)
})
}

To support this change, we need to update EmailClientModel to add this new AddEmail() function. The function will add an item to the list and publish the data-reset event:

func (e *EmailClientModel) AddEmail(email *client.EmailMessage) {
e.root.Add(email)
e.itemsResetPublisher.Publish(e.root)
}

This, in turn, needs an Add() function in the InboxList type that we created to provide data to the model:

func (i *InboxList) Add(email *client.EmailMessage) {
i.emails = append(i.emails, &EmailModel{email, i})
}

Finally, we need to listen to the Incoming() server channel, which will deliver each new email to our application. As this channel read will block until an email is received, this must run in a separate goroutine—hence the background processing. When an email arrives, we simply call the function we just created, passing the new email and a reference to the model which we should refresh:

server := client.NewTestServer()
model.SetServer(server)

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

With this code in place, you will see the email list update when a new email arrives. The email can then be clicked to see the details.

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

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