## Draft for Wishlist Sync Manager ``` public final class WishListSyncManager { let shared = WishListSyncManager() let wishListRepo: WishListrepo let localStorage: FileStorage var remoteWishList: [RemoteWishListObj] = []() func syncWishList() { Task(priority: .userInitiated, operation: { remoteWishList = remoteWishList() let (addItemList, deleteItemList) = await( try? findWishListItemsToAdd(remoteWishList), try? findWishListItemsToDelete(remoteWishList)) async let addItemsTask = wishListRepo.addItemToWishList(addItemList) async let deleteItemsTask = wishListRepo.deleteItemFromWishList(deleteItemList) let (addedItems, deleteItems) = await(try? addItemsTask, try? deleteItemsTask) // fire base forget }) } func remoteWishList() async -> [WishListObj] { [WishlistObj, WishlistObj] } /// run on first cold launch of app or when user sign in to app to check if migration needed func wishlistMigration() async { let remoteWishList = getRemoteWishList() let localWishList = localStorage.getWishList() if remoteWishList.isEmpty, !localWishList.isEmpty { await wishListRepo.addItemToWishList(localWishList) } } func findWishListItemsToAdd(remoteWishList: RemoteWishList) async -> [String] { ["xxxx"] } func findWishListItemsToDelete(remoteWishList: RemoteWishList) async -> [String] { ["xxxx"] } init(wishListRepo: WishListrepo, localStorage: FileStorage) { self.wishListRepo = wishListRepo self.localStorage = localStorage } } ``` ## Below is the refined algorithm ``` /// Scenario: Local delete 1,2 and added 3, 4 var remoteList = ["1", "2", "7", "8", "9"] // start get remote wish list. class property let updatedRemoteList = ["1", "2", "8", "10"] // adds 10, this list will get from api while syncing wish list, this is local variable in function let localList = ["8","9", "3", "4"] // 1, 2 deleted, [8,3,4,10] let distinctUnique = Array(Set(updatedRemoteList + localList)).sorted() let itemToAdd = Set(distinctUnique).subtracting(remoteList) print(itemToAdd) let remoteAddedItems = Set(updatedRemoteList).subtracting(remoteList) let finalItemToAdd = itemToAdd.subtracting(remoteAddedItems) let remoteDeletedItems = Set(remoteList).subtracting(updatedRemoteList) let itemToDelete = Set(remoteList).subtracting(localList) // run this in playground. This will give us the list that we want let finalItemToDelete = itemToDelete.subtracting(remoteDeletedItems) remoteList = Set(localList + remoteAddedItems).subtracting(remoteDeletedItems).sorted() // assign back this result to class remoteList property ```