Ad

Webflux Is Returning Initial Response Only, When Calling Another Reactive Api

I'm creating a crypto monitoring app. I want to call another reactive API from spring boot inside the current project. But unfortunately, I'm only getting an initial response from flux. In simple words, I'm not getting a stream of data on the client side.

Spring Boot Code

@RestController
public class SseController {
    private final WebClient webClient = WebClient.create();
    @GetMapping(value ="/emitter",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> startStreaming() {
        return webClient.get()
                .uri("https://api.wazirx.com/api/v2/tickers")
                .retrieve()
                .bodyToFlux(String.class); 
    }
}

Flutter Code

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var stream ;
  @override
  void initState() {
    super.initState();
    var sseClient = SseClient.connect(Uri.parse('http://localhost:8080/emitter'));
     stream = sseClient.stream;
    if (stream == null) {
      print('Stream is not connected');
      return;
    }
    stream.listen((event) {
      //print(event);// event is a String
      final data =jsonDecode(event);
      print(data["btcinr"]["last"]);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SSE',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Receive SSE Events'),
        ),
        body: Center(
          child: Text('Some')
        ),
      ),
    );
  }
}

The flutter code is working as expected I have tested It. You can also try buy running it.

Ad

Answer

It's because the api you are calling is not producing a stream of data.

If you read the api for Wazirx it clearly states that the link you are accessing /api/v2/tickers returns:

Returns JSON response which has active market data with all ticker related values.

This can be confirmed if you copy paste the link into a browser and look at the request made, it returns a application/json and not a event stream so if you want real time data, you have to either poll this endpoint at regular intervals, or find another api to call.

Ad
source: stackoverflow.com
Ad