Phuoc
Phuoc

Reputation: 1116

Flutter merge multiple streams flutter to perform OR queries in firestore

In this code I try to retrieve data match this logic: if (title == query || subtitle == query). Here my code using MergeStream of RxDart:

  //if (title == query)
  Stream<QuerySnapshot> searchProgramsByTitle(String query) async* {
    if (query.length == 0) {
      yield* fireStore.collection('programs').orderBy('listened', descending: true).snapshots();
    }
    else {
      yield* fireStore.collection('programs').where('title', isEqualTo: query).orderBy('listened', descending: true).snapshots();
    }
  }
  
  //if (subtitle == query)
  Stream<QuerySnapshot> searchProgramsBySubtitle(String query) async* {
    if (query.length == 0) {
      yield* fireStore.collection('programs').orderBy('listened', descending: true).snapshots();
    }
    else {
      yield* fireStore.collection('programs').where('subtitle', isEqualTo: query).orderBy('listened', descending: true).snapshots();
    }
  }
  
  // OR query
  Stream<QuerySnapshot> searchPrograms(String query) async* {
    Stream<QuerySnapshot> stream1 = searchProgramsByTitle(query);
    Stream<QuerySnapshot> stream2 = searchProgramsBySubtitle(query);
    yield* MergeStream([stream1, stream2]);
  }

searchProgramsByTitle and searchProgramsBySubtitle work fine seperately. But searchPrograms doesn't work. What am I missing ?

Upvotes: 1

Views: 386

Answers (1)

Phuoc
Phuoc

Reputation: 1116

Thanks to these lovely answers of pskink. I manage to solve this problem:


  Stream<List> searchPrograms(String query) async* {
    Stream<QuerySnapshot> stream1 = searchProgramsByTitle(query);
    Stream<QuerySnapshot> stream2 = searchProgramsBySubtitle(query);
    yield* rx.CombineLatestStream.combine2(stream1, stream2, (QuerySnapshot a, QuerySnapshot b) => [...a.docs.map((e) => e.id), ...b.docs.map((e) => e.id)]);
  }

Upvotes: 1

Related Questions