Last active
October 20, 2017 05:19
-
-
Save JavadocMD/e954180533b4f67a511b1cfd19145b14 to your computer and use it in GitHub Desktop.
UniRx Before and After Example: loading a catalog from a web API while falling back to two on-disk sources.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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