4

I'm trying to make an Http Client call in flutter with content-type:application/stream+json and accept: application/stream+json,in order to use reactive response from the backend but this is what the response looks like:

{"name":"bobby", "lastname": "fisher"}
{"name":"dominic", "lastname": "thiem"}
{"name":"roger", "lastname": "federer"}
{"name":"a", "lastname": "b"}
{"name":"c", "lastname": "d"}
{"name":"e", "lastname": "f"}

without [ ] and , so how I can iterate on it?

PD: If I send application/json works but not reactive way.

Any help?

Stukz
  • 51
  • 3

1 Answers1

0

So, there's two steps we need to take here:

  1. Get a raw byte stream from the network
  2. Transform that stream into a json stream

Using dio, we can get the stream like this:

final response = await dio.get<ResponseBody>(
  '/streaming/url',
  options: Options(
    responseType: ResponseType.stream,
  ),
);

// Check status code, etc...

final responseStream = response.data!.stream;

Once we have a stream, we'll need to decode it into text, split it by line, and parse the json. This part will be identical regardless of if you're using dio or not.

utf8.decoder
    .bind(responseStream)
    .transform(const LineSplitter())
    .map((line) => jsonDecode(line));

So, the final method might look something like this

Stream<dynamic> subscribeToStream() async* {
  final response = await dio.get<ResponseBody>(
    '/streaming/url',
    options: Options(
      responseType: ResponseType.stream,
    ),
  );

  // check status, etc

  yield* utf8.decoder
      .bind(response.data!.stream)
      .transform(const LineSplitter())
      .map((line) => jsonDecode(line));
}
iCodeSometime
  • 1,444
  • 15
  • 30