Starting offline

The preceding strategies help to deal with intermittent internet connections, or continuing to work with an application in offline mode after some time online. But what if your application is designed to work offline right from the first usage? If a login isn't required immediately, then you may be able to support an initial offline state; probably not ideal for an email client but it may be expected for a collaborative documentation platform or entertainment system. How can we make use of the techniques we've explored already to provide a great first-use experience if there's no network available?

The simplest approach to this problem is probably to package data with the application so that it can be used as a cache if no recently cached data is available. In this manner, the application could attempt to use a local cache if one exists, then fall back to the application data otherwise, and if neither is available, then attempt to make the remote connection, like the following prototypical function:

func cacheFallbackStream(url string) io.ReadCloser {
stream := cacheStream(url)
if stream != nil {
return stream
}

stream = resourceStream(url)
if stream != nil {
return stream
}

return readStream(url)
}

In this example, we re-use the cacheStream() and readStream() functions before and  use a new (hypothetical) function named resourceStream(), which would encode the URL, look up some bundled resources in the application, and return a stream to one if it's found. An alternative approach is for the first run of an application to extract all of the cached resources it has packaged and set up a local cache, then later code could simply use cacheStream() as before. For more information about bundling resources for distribution, see Chapter 14, Distributing your Application.

Of course, whichever strategy you use, be sure to consider how important it is for the data to be up to date; is falling back to an old cache that's bundled in the application a good strategy for your data? Do you want to update the local copy of this information on a regular basis? If it's important that the data be as fresh as possible, then the preceding function should probably be changed so that readStream() is attempted before resourceStream() or even cacheStream() and a live request is attempted if possible. If you take this approach, be sure to consider timeouts and other failure conditions, and handle user expectations appropriately.

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

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