Search code examples
iphoneswiftcocoa-touchreactive-cocoareactive-swift

How to interrupt SafeSignal in ReactiveSwift?


Hi I am new to reactive swift. In my new project I am using ReactiveSwift. I am observing value by using SafeSignal variable. I want to interrupt the signal before getting the value. Please help me out in this issue.


Solution

  • In general, when you observe on a Signal or start a SignalProducer, you will get a Disposable back.

    This can be used to end the observation:

    let property = MutableProperty<Int>(0)
    let signalDisposable = property.signal.observeValues {
      print("Signal: \($0)")
    }
    
    let producerDisposable = property.producer.startWithValues {
      print("Producer: \($0)")
    }
    
    
    property.value = 1            // Signal and Producer receive value 1
    signalDisposable?.dispose()   // End signal observation
    property.value = 2            // Only producer receives value 2
    producerDisposable.dispose()  // End producer observation
    property.value = 3            // No one receives value 3
    

    Cancelation of running work

    If you're creating your own SignalProducer for some (longer) work, you'll have to keep disposal in mind in order to stop ongoing work:

    let performNetworkCall = SignalProducer<Data, Error> { (observer, disposable) in
      let url = URL(string: "https://www.download.com")!
      let downloadTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, _, error) in
        // Handle completion
      })
      downloadTask.resume()
      disposable.observeEnded {
        // Cancel the download on disposal!
        downloadTask.cancel()
      }
    }
    

    Otherwise, your observer will be detached, but the work started by the observer will still resume