0

I try to get List from jsonPlaceHolder using flutter rxdart stream and try to apply bloc pattern on it.

this class that response for get post response from api

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/post_item.dart';

class ItemApi {

  Future<List<JsonItem>> getPost() async {
    String _url = 'https://jsonplaceholder.typicode.com/posts';

    final _response = await http.get(_url);

    if (_response.statusCode == 200) {
      return (json.decode(_response.body) as List)
          .map((jsonItem) => JsonItem.fromJson(jsonItem))
          .toList();
    }
  }

}

I using repository class to wrap using ItemApi class

import 'json_item_request.dart';
import '../models/post_item.dart';

class Repository{

  final jsonItemResponse = ItemApi();
  Future<List<JsonItem>> getItem() => jsonItemResponse.getPost();


}

at the last i using bloc class that response for get data and set it inside PublishSubject

import '../models/post_item.dart';
import '../resouces/repository.dart';
import 'package:rxdart/rxdart.dart';

class JsonBloc {
  final _repository = Repository();
  final _streamOfJsonList = PublishSubject<List<JsonItem>>();


  Observable<List<JsonItem>> get jsonList=> _streamOfJsonList.stream;


  fetchAllPost() async{
    Future<List<JsonItem>> list = _repository.getItem();

  }

  dispose(){
    _streamOfJsonList.close();
  }


}

My question is how i can set response inside _streamOfJsonList variable to using it when list changed.

2 Answers2

0

Sounds like you already have all the moving parts connected? If so you just need to add the item list to the PublishSubject:

void fetchAllPost() async {
  List<JsonItem> list = await _repository.getItem();
  _streamOfJsonList.add(list);
}

This will trigger the onListen callback with the new list on anything that is listening to the stream.

Edman
  • 5,335
  • 29
  • 32
0

You can add error and data to ReplaySubject like below :

 void fetchAllPost() async {
    List<JsonItem> list = await _repository.getItem();
    if (list != null) {
      _streamOfJsonList.sink.add(list);
    } else {
      _streamOfJsonList.addError("ERROR");
    }
  }
Maya Mohite
  • 675
  • 6
  • 8