Imgkl / EventFlux

A Dart package for efficient handling of server-sent event streams with easy connectivity and data management.
https://pub.dev/packages/eventflux
MIT License
25 stars 8 forks source link

This expression has a type of 'void' so its value can't be used #19

Closed bleymambwe closed 5 months ago

bleymambwe commented 5 months ago

It appears the example documented on the flutter package does not compiles with the following errors

'This expression has a type of 'void' so its value can't be used. Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.' it also says something about ' onSuccessCallback: () ' being required

Imgkl commented 5 months ago

Hey @bleymambwe,

Thanks for pointing this out. The example was a remnant of old implementation. I've removed it now.

You can checkout this link on how to use EventFlux.

bleymambwe commented 5 months ago

Thank you for your response and update, it worked but I still have one issue which I seem to be having with almost all packages, that is response is only returned after it completes rather than in real time.

I want to develop a chatbot, using some LLM, i therefore want a reliable package to show real time response streaming. I wrote some simple number generate in Python to show as follows ;

import asyncio
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI
from sse_starlette.sse import EventSourceResponse
import random

app = FastAPI()

async def numbers(minimum, maximum):
    for i in range(minimum, maximum + 1):
        await asyncio.sleep(random.uniform(0.2, 2))
        yield dict(data=i)

@app.get("/sse")
async def sse():
    generator = numbers(1, 15)
    return EventSourceResponse(generator)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow requests from all origins
    allow_credentials=True,
    allow_methods=["GET"],  # Allow GET requests
    allow_headers=["*"],  # Allow all headers
)

In Python I use the following code to test the endpoint and works well, receiving the data in real time.

import requests

def event_stream():
    url = 'http://localhost:8000'
    response = requests.get(url, stream=True)

    for line in response.iter_lines():
        if line:
            yield line.decode('utf-8')

if __name__ == "__main__":
    for event in event_stream():
        print(event)

I would like to do something similar in flutter, here is my attempt.

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:eventflux/client.dart';
import 'package:eventflux/eventflux.dart';

class StreamTest extends StatefulWidget {
  @override
  _StreamTestState createState() => _StreamTestState();
}

class _StreamTestState extends State<StreamTest> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stream Test'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                connectToStream(); // Added missing semicolon
              },
              child: Text('Request Data'),
            ),
          ],
        ),
      ),
    );
  }
}

void connectToStream() {
  // Moved connectToStream outside the class definition
  EventFlux.instance.connect(
    EventFluxConnectionType.get,
    '<local host or something>',
    onSuccessCallback: (EventFluxResponse? response) {
      response!.stream?.listen((data) {
        // Your data is now in the spotlight!
        // print(data.data);
        print('success $data.data');
      });
    },
    onError: (oops) {
      // how do i catch the exact error
      print('something went wrong ');
    },
    autoReconnect: false,
    // reconnectConfig: ReconnectConfig(
    //   mode: ReconnectMode.linear, // Corrected '=' to ':'
    //   interval: Duration(seconds: 5),
    //   maxAttempts: 5, // Corrected '=' to ':'
    //   onReconnect: () {
    //     // Things to execute when reconnect happens
    //     // FYI: for network changes, the `onReconnect` will not be
called.
    //     // It will only be called when the connection is interrupted by
the server and eventflux is trying to reconnect.
    //   },
    // ),
  );
}

On Wed, 15 May 2024 at 18:12, Sai Gokula Krishnan @.***> wrote:

Hey @bleymambwe https://github.com/bleymambwe,

Thanks for pointing this out. The example was a remnant of old implementation. I've removed it now.

You can checkout this link https://github.com/Imgkl/EventFlux?tab=readme-ov-file#how-to-use-spoiler-its-super-easy- on how to use EventFlux.

— Reply to this email directly, view it on GitHub https://github.com/Imgkl/EventFlux/issues/19#issuecomment-2112952504, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMLHYGFOWTFH7FU47KWFLN3ZCOCOXAVCNFSM6AAAAABHXVJO6CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMJSHE2TENJQGQ . You are receiving this because you were mentioned.Message ID: @.***>