getTracks method

Stream<Iterable<Track>> getTracks(
  1. int playlistId, {
  2. int offset = defaultOffset,
  3. int limit = defaultLimit,
})

Gets batches of tracks contained in the playlist with the specified playlistId.

Implementation

Stream<Iterable<Track>> getTracks(
  int playlistId, {
  int offset = defaultOffset,
  int limit = defaultLimit
}) async* {
  throwIfNegative(offset, 'offset');
  throwIfNegative(limit, 'limit');

  final json = await _getPlaylistResponse(playlistId);
  final tracks = json['tracks'] as List;
  final trackIds = tracks.map((t) => t['id'] as int);

  final clientId = await _controller.getClientId();

  var continuationOffset = offset;

  while (true) {
    final batchIds = trackIds.skip(continuationOffset).take(limit);

    if (batchIds.isEmpty) return;

    final idsParam = batchIds.join(',');

    final uri = Uri.https(
      'api-v2.soundcloud.com',
      '/tracks', {
        'ids': idsParam,
        'client_id': clientId
      }
    );

    final response = await _http.get(uri);
    response.ensureSuccessStatusCode();
    final actualTracks = jsonDecode(response.body) as List;

    yield actualTracks.map((t) => Track.fromJson(t));

    continuationOffset += actualTracks.length;
  }
}