Search code examples
androidkotlinrx-javareactivexrx-kotlin

To Kill an Observable


Excuse the pun, had to do it to em.

I have an observable that is declared like so:

Observable
        .interval(20, TimeUnit.MILLISECONDS)
        .subscribe {
            val timeDiff = System.currentTimeMillis() - testSum
            Log.i("LOG", "TIME DIFF: $timeDiff")
            testSum = System.currentTimeMillis()

            mVisualizer.getWaveForm(waveformByteArray)
            onWaveFormDataCaptureManual(waveformByteArray)
        }

And no matter what I try to do, this observable will not die. disposables.add() (which seems to be the answer in Java) gives me an unresolved reference error. Before that, I can't even save it to a variable either, as that also shows a lot of red on the screen.

FYI I've Googled this problem. Nothing works.


Solution

  • You need to take the output disposable and dispose it

    import io.reactivex.disposables.Disposable  //required import
    
     var diposable:Disposable?=null   //global variable
    
    
       disposable= Observable
                .interval(20, TimeUnit.MILLISECONDS)
                .subscribe {
                    val timeDiff = System.currentTimeMillis() - testSum
                    Log.i("LOG", "TIME DIFF: $timeDiff")
                    testSum = System.currentTimeMillis()
    
                    mVisualizer.getWaveForm(waveformByteArray)
                    onWaveFormDataCaptureManual(waveformByteArray)
                }
    

    to dispose use

     disposable?.dispose()
    

    If you have multiple disposables then you can use CompositeDisposable

     var compositeDisposable:CompositeDisposable= CompositeDisposable()
    
     val disposable= Observable
            .interval(20, TimeUnit.MILLISECONDS)
            .subscribe {
                val timeDiff = System.currentTimeMillis() - testSum
                Log.i("LOG", "TIME DIFF: $timeDiff")
                testSum = System.currentTimeMillis()
    
                mVisualizer.getWaveForm(waveformByteArray)
                onWaveFormDataCaptureManual(waveformByteArray)
            }
    
         compositeDisposable.add(disposable)
        // you can add as many disposables as you want
    

    to Dispose use

       compositeDisposable.dispose()  //every thing is disposed