C# combine two observables which returning json, then parse json into array of model item
- User
C# combine two observables which returning json, then parse json into array of model item
- Assistant
- User
Same but use combine latest
- Assistant
Sure! Here's an example that uses
CombineLatestinstead ofZipto combine two observables that emit JSON strings, parses each JSON into an array of your modelItem, then combines both arrays into a single array:using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text.Json; public class Item { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main() { var observable1 = Observable.Return("[{\"Id\":1,\"Name\":\"A\"}]"); var observable2 = Observable.Return("[{\"Id\":2,\"Name\":\"B\"}]"); var combined = observable1.CombineLatest(observable2, (json1, json2) => { // Deserialize both JSON arrays into lists var list1 = JsonSerializer.Deserialize<List<Item>>(json1); var list2 = JsonSerializer.Deserialize<List<Item>>(json2); // Combine lists into one var combinedList = new List<Item>(); if (list1 != null) combinedList.AddRange(list1); if (list2 != null) combinedList.AddRange(list2); return combinedList.ToArray(); }); combined.Subscribe(items => { foreach (var item in items) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}"); } }); Console.ReadLine(); } }