All Downloads are FREE. Search and download functionalities are using the official Maven repository.

monix.reactive.internal.operators.SwitchMapObservable.scala Maven / Gradle / Ivy

Go to download

Sub-module of Monix, exposing the Observable pattern for modeling of reactive streams. See: https://monix.io

The newest version!
/*
 * Copyright (c) 2014-2021 by The Monix Project Developers.
 * See the project homepage at: https://monix.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package monix.reactive.internal.operators

import monix.execution.Ack.{Continue, Stop}
import monix.execution.cancelables.{CompositeCancelable, SerialCancelable, SingleAssignCancelable}
import scala.util.control.NonFatal
import monix.execution.{Ack, Cancelable}
import monix.reactive.observers.Subscriber
import monix.reactive.{Observable, Observer}

import scala.concurrent.Future

private[reactive] final class SwitchMapObservable[A, B](source: Observable[A], f: A => Observable[B])
  extends Observable[B] {

  def unsafeSubscribeFn(out: Subscriber[B]): Cancelable = {
    val activeChild = SerialCancelable()
    val mainTask = SingleAssignCancelable()
    val composite = CompositeCancelable(activeChild, mainTask)

    mainTask := source.unsafeSubscribeFn(new Subscriber.Sync[A] { self =>
      implicit val scheduler = out.scheduler
      // MUST BE synchronized by `self`
      private[this] var ack: Future[Ack] = Continue
      // MUST BE synchronized by `self`
      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
        else {
          // Protects calls to user code from within the operator.
          val childObservable =
            try f(elem)
            catch {
              case ex if NonFatal(ex) =>
                Observable.raiseError(ex)
            }

          ack = ack.syncTryFlatten
          activeChildIndex += 1
          val myChildIndex = activeChildIndex

          activeChild := childObservable.unsafeSubscribeFn(new Observer[B] {
            def onNext(elem: B) =
              self.synchronized {
                if (myChildIndex != activeChildIndex)
                  Stop
                else {
                  ack = out.onNext(elem).syncOnStopOrFailure { _ => cancelFromDownstream(); () }
                  ack
                }
              }

            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)
                  self.onError(ex)
              }
          })

          Continue
        }
      }

      def cancelFromDownstream(): Ack = self.synchronized {
        if (upstreamIsDone) Stop
        else {
          upstreamIsDone = true
          activeChildIndex = -1
          ack = Stop
          mainTask.cancel()
          Stop
        }
      }

      def onError(ex: Throwable): Unit = self.synchronized {
        if (!upstreamIsDone) {
          upstreamIsDone = true
          activeChildIndex = -1
          composite.cancel()
          out.onError(ex)
        }
      }

      def onComplete(): Unit = self.synchronized {
        if (!upstreamIsDone) {
          upstreamIsDone = true
          if (lastChildIsDone) {
            activeChildIndex = -1
            out.onComplete()
          }
        }
      }
    })

    composite
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy