Skip to content

Instantly share code, notes, and snippets.

@iKenndac
Created April 12, 2012 15:17
Show Gist options
  • Save iKenndac/2368081 to your computer and use it in GitHub Desktop.
Save iKenndac/2368081 to your computer and use it in GitHub Desktop.
Waiting for multiple tiers to load in an object graph
/*
This method uses a blocks-based callback mechanism to handle the async process in which
most objects in the CocoaLibSpotify pbject graph use.
This is an example of how to improve the method -waitAndFillTrackPool in the CocoaLibSpotify
"Guess The Intro" sample, which calls the same method repeatedly until enough loaded tracks
are found.
The code below waits until the session is loaded, then the userPlaylists list, then the
playlists themselves, then all of the tracks within those playlists. Once the tracks have
loaded their metadata, the game is started.
*/
-(void)fillTrackPool {
[SPAsyncLoadingObserver waitUntilLoaded:[NSArray arrayWithObject:[SPSession sharedSession]] then:^(NSArray *loadedession) {
// The session is logged in and loaded — now wait for the userPlaylists to load.
NSLog(@"Session loaded.");
[SPAsyncLoadingObserver waitUntilLoaded:[NSArray arrayWithObject:[SPSession sharedSession].userPlaylists] then:^(NSArray *loadedContainers) {
// User playlists are loaded — wait for playlists to load their metadata.
NSLog(@"Container loaded.");
NSMutableArray *playlists = [NSMutableArray array];
[playlists addObject:[SPSession sharedSession].starredPlaylist];
[playlists addObject:[SPSession sharedSession].inboxPlaylist];
[playlists addObjectsFromArray:[SPSession sharedSession].userPlaylists.flattenedPlaylists];
[SPAsyncLoadingObserver waitUntilLoaded:playlists then:^(NSArray *loadedPlaylists) {
// All of our playlists have loaded their metadata — wait for all tracks to load their metadata.
NSLog(@"All playlists loaded.");
NSArray *playlistItems = [loadedPlaylists valueForKeyPath:@"@unionOfArrays.items"];
NSArray *tracks = [self tracksFromPlaylistItems:playlistItems];
[SPAsyncLoadingObserver waitUntilLoaded:tracks then:^(NSArray *loadedTracks) {
// All of our tracks have loaded their metadata. Hooray!
NSLog(@"All tracks loaded.");
NSMutableArray *theTrackPool = [NSMutableArray arrayWithCapacity:loadedTracks.count];
for (SPTrack *aTrack in loadedTracks) {
if (aTrack.availability == SP_TRACK_AVAILABILITY_AVAILABLE && [aTrack.name length] > 0)
[theTrackPool addObject:aTrack];
}
self.trackPool = [NSMutableArray arrayWithArray:[[NSSet setWithArray:theTrackPool] allObjects]];
// ^ Thin out duplicates.
[self startNewRound];
}];
}];
}];
}];
}
@tbass134
Copy link

great thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment