Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ private[reactive] final class SwitchMapObservable[A, B](source: Observable[A], f
private[this] var activeChildIndex: Int = -1
// MUST BE synchronized by `self`
private[this] var upstreamIsDone: Boolean = false
// MUST BE synchronized by `self`
private[this] var lastChildIsDone: Boolean = false

def onNext(elem: A): Ack = self.synchronized {
if (upstreamIsDone) Stop
Expand All @@ -61,15 +63,24 @@ private[reactive] final class SwitchMapObservable[A, B](source: Observable[A], f
activeChild := childObservable.unsafeSubscribeFn(new Observer[B] {
def onNext(elem: B) =
self.synchronized {
if (upstreamIsDone || myChildIndex != activeChildIndex)
if (myChildIndex != activeChildIndex)
Stop
else {
ack = out.onNext(elem).syncOnStopOrFailure(_ => cancelFromDownstream())
Comment thread
Avasil marked this conversation as resolved.
ack
}
}

def onComplete(): Unit = ()
def onComplete(): Unit = self.synchronized {
if (myChildIndex == activeChildIndex) {
if (upstreamIsDone) {
activeChildIndex = -1
out.onComplete()
} else {
lastChildIsDone = true
}
}
}
def onError(ex: Throwable): Unit =
self.synchronized {
if (myChildIndex == activeChildIndex)
Expand Down Expand Up @@ -104,9 +115,10 @@ private[reactive] final class SwitchMapObservable[A, B](source: Observable[A], f
def onComplete(): Unit = self.synchronized {
if (!upstreamIsDone) {
upstreamIsDone = true
activeChildIndex = -1
activeChild.cancel()
out.onComplete()
if (lastChildIsDone) {
activeChildIndex = -1
out.onComplete()
}
}
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,14 @@ object SwitchMapSuite extends BaseOperatorSuite {
assertEquals(r2.value.get, r1.value.get)
}

test("switchMap should cancel child after stream has ended") { implicit s =>
val source = Observable.now(1L).switchMap { x =>
Observable.intervalWithFixedDelay(1.second, 1.second).map(_ + x)
}

var total = 0L
source.unsafeSubscribeFn(new Observer.Sync[Long] {
def onNext(elem: Long): Ack = {
total += elem
Continue
}

def onError(ex: Throwable): Unit = throw ex
def onComplete(): Unit = ()
})

s.tick()
assertEquals(total, 0)
assert(s.state.tasks.isEmpty, "tasks.isEmpty")
test("Observable.unit.switchMap(_ => a) <-> a") { implicit s =>
val expectedCount = 100
val size = Observable.unit
.switchMap(_ => Observable.interval(1.second).take(expectedCount))
.countL
.runToFuture

s.tick(1.day)
assertEquals(size.value.get.get, expectedCount)
}
}