Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UniRx Before and After Example: loading a catalog from a web API while falling back to two on-disk sources.
// First the solution as provided, using UniRx.
public class ObservablesExample {
// The CatalogInfo, this is non-null immediately after calling LoadCatalog().
public IObservable<CatalogInfo> CatalogInfo;
// Helper methods, where the work of loading is done.
// UniRx makes it painless to execute these off the main thread.
// Errors are handled by Observable.OnError
private IObservable<CatalogInfo> LoadFromPlayFab() { /* ... */ }
private IObservable<CatalogInfo> LoadFromDisk() { /* ... */ }
private IObservable<CatalogInfo> LoadFromAsset() { /* ... */ }
public void LoadCatalog() {
CatalogInfo = PlayFabInit.PlayFabId
.ContinueWith(LoadFromPlayFab())
.Catch((Exception e) => LoadFromDisk())
.Catch((Exception e) => LoadFromAsset());
}
}
// And now the solution using standard C#.
public class NoObservablesExample {
// The CatalogInfo, this is null for some indeterminate time after calling LoadCatalog().
public CatalogInfo CatalogInfo;
// Helper methods, where the work of loading is done.
// Errors throw Exceptions
private CatalogInfo LoadFromPlayFab() { /* ... */ }
private CatalogInfo LoadFromDisk() { /* ... */ }
private CatalogInfo LoadFromAsset() { /* ... */ }
public void LoadCatalog() {
new Thread(LoadCatalogFirstStep).Start();
}
private void LoadCatalogFirstStep() {
if (PlayFabInit.PlayFabId != null) {
// Assume PlayFabId is null if we're not connected.
CatalogInfo = LoadCatalogFallback();
return;
}
try {
CatalogInfo = LoadFromPlayFab();
} catch (Exception) {
CatalogInfo = LoadCatalogFallback();
}
}
private CatalogInfo LoadCatalogFallback() {
try {
return LoadFromDisk();
} catch (Exception) {
return LoadFromAsset(); // Assuming this never fails.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment