我有两个集合。 home
和device
。我需要调用home
集合并从home_id
获取home
,然后将条件添加到device
集合查询中。
在完成代码之前,_home$.add(_homeListData)
正在触发,并且homeModel.device
数据也是重复的
第一次运行应用程序时,The getter 'devices' was called on null.
String id;
List<Device> _d = [];
var stream1 = databaseReference
.collection('home-management')
.where("homeAdmin", isEqualTo: userID);
await stream1.getDocuments().then((data) {
data.documents.forEach((doc) {
id = doc.documentID;
});
});
Stream<QuerySnapshot> stream2 = databaseReference
.collection('devices')
.where("homeId", isEqualTo: id)
.snapshots();
Observable.merge([stream1.snapshots(), stream2]).listen((data) {
data.documents.forEach((doc) {
TempModel.fromFirestore(doc);
if (doc.data['homeName'] != null) {
homeModel.home = Home.fromDocument(doc);
} else {
_d.add(Device.fromDocument(doc));
homeModel.devices = _d;
}
_homeListData.add(homeModel);
_home$.add(_homeListData); // before complete above code, this one is firing, and also homeModel.device data duppplicate
});
});
完整的单例课程
class HomeAndDeviceService {
static final databaseReference = Firestore.instance;
static List<HomeModel> _homeListData = new List<HomeModel>();
static final HomeAndDeviceService _singleton =
HomeAndDeviceService._internal();
static String userID;
// static ReplaySubject<List<HomeModel>> _home$ =
// ReplaySubject<List<HomeModel>>();
static BehaviorSubject<List<HomeModel>> _home$ =
BehaviorSubject<List<HomeModel>>();
factory HomeAndDeviceService(String _userID) {
userID = _userID;
return _singleton;
}
HomeAndDeviceService._internal() {
getHomeData();
}
BehaviorSubject<List<HomeModel>> getHomes() {
return _home$;
}
static getHomeData() async {
HomeModel homeModel = new HomeModel();
//add here to above code