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

com.noheltcj.rxcommon.operators.SwitchMap.kt Maven / Gradle / Ivy

package com.noheltcj.rxcommon.operators

import com.noheltcj.rxcommon.Source
import com.noheltcj.rxcommon.disposables.Disposable
import com.noheltcj.rxcommon.disposables.Disposables
import com.noheltcj.rxcommon.emitters.ColdEmitter
import com.noheltcj.rxcommon.emitters.Emitter
import com.noheltcj.rxcommon.observers.AllObserver
import com.noheltcj.rxcommon.observers.Observer

/**
 * This class will not listen to any upstream dispose notifications other than the original source.
 */
class SwitchMap(
    private val upstream: Source,
    private val resolveNewSource: (U) -> Source
) : Operator() {

  override val emitter: Emitter = ColdEmitter {}

  private var currentSecondaryDisposable: Disposable? = null
  private var sourceCompleted = false
  private var newSourceCompleted = true

  override fun subscribe(observer: Observer): Disposable {
    emitter.addObserver(observer)

    val upstreamDisposable = upstream.subscribe(
        AllObserver(
          onNext = {
            newSourceCompleted = false
            val tempDisposable = resolveNewSource(it).subscribe(this)
            currentSecondaryDisposable?.dispose()
            currentSecondaryDisposable = tempDisposable
          },
          onError = {
            currentSecondaryDisposable?.dispose()
            emitter.terminate(it)
          },
          onComplete = {
            sourceCompleted = true
            if(newSourceCompleted)
              emitter.complete()
          }
        )
    )

    return Disposables.create {
      upstreamDisposable.dispose()
      currentSecondaryDisposable?.dispose()
      emitter.removeObserver(observer)
    }
  }

  override fun onComplete() {
    newSourceCompleted = true
    if (sourceCompleted)
      super.onComplete()
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy