Skip to content

Instantly share code, notes, and snippets.

@devxoul
Last active April 16, 2020 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devxoul/b093c71b50022c666f57bdd61be79db3 to your computer and use it in GitHub Desktop.
Save devxoul/b093c71b50022c666f57bdd61be79db3 to your computer and use it in GitHub Desktop.
RxSwift Observable<(T, T)>.distinctUntilChanged() returns wrong result
let source = Observable<(Int, Int)>.from([
(0, 1),
(2, 3),
(4, 5),
])
// Doesn't work as expected
// A -> (0, 1)
source
.distinctUntilChanged(==)
.subscribe(onNext: { print("A ->", $0) })
print()
// Doesn't work as expected
// B -> (0, 1)
source
.distinctUntilChanged { $0 == $1 }
.subscribe(onNext: { print("B ->", $0) })
print()
// Doesn't work as expected
// C -> (0, 1)
source
.distinctUntilChanged { old, new in old == new }
.subscribe(onNext: { print("C ->", $0) })
print()
// Works as expected
// D -> (0, 1)
// D -> (2, 3)
// D -> (4, 5)
source
.distinctUntilChanged { "\($0)" == "\($1)" }
.subscribe(onNext: { print("D ->", $0) })
print()
// Works as expected
// E -> (0, 1)
// E -> (2, 3)
// E -> (4, 5)
source
.distinctUntilChanged { (); return $0 == $1 }
.subscribe(onNext: { print("E ->", $0) })
print()
// Works as expected
// F -> (0, 1)
// F -> (2, 3)
// F -> (4, 5)
source
.distinctUntilChanged { let _ = (); return $0 == $1 }
.subscribe(onNext: { print("F ->", $0) })
print()
@devxoul
Copy link
Author

devxoul commented Apr 16, 2020

Related issue: ReactiveX/RxSwift#2097

@tokijh
Copy link

tokijh commented Apr 16, 2020

How about

source
  .distinctUntilChanged { (old: (Int, Int), new: (Int, Int)) in old == new }
  .subscribe(onNext: { print("G ->", $0) })
print()

This case expected to following

// G -> (0, 1)
// G -> (2, 3)
// G -> (4, 5)

This case works as expected!
I tested this case with RxSwift 5.1.1 and Swift 5.1.3

@devxoul
Copy link
Author

devxoul commented Apr 16, 2020

Yeah that would definitely work, but what I wanted to do is to not specify types so that Swift compiler could infer the types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment