Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.coderefer.rxandroidexamples.intro.operators.create
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.coderefer.rxandroidexamples.R
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
private const val TAG = "DeferOperatorActivity"
class DeferOperatorActivity : AppCompatActivity() {
private lateinit var disposable1 :Disposable
private lateinit var disposable2 :Disposable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_defer_operator)
val testClass = TestClass()
val observable = testClass.strObservable()
val deferObservable = testClass.deferObservable()
testClass.str = "World"
disposable1 = observable.subscribe {
Log.d(TAG, it) // prints "Hello" only since it is the value when Observable is created / initialized
}
observable.subscribe()
disposable2 =deferObservable.subscribe {
Log.d(TAG, it) // prints "World" since it creates a fresh Observable when subscribed with fresh data.. hence prints "World"
}
}
override fun onDestroy() {
disposable1.dispose() // to avoid memory leaks
disposable2.dispose()
super.onDestroy()
}
}
class TestClass {
var str: String? = "Hello"
fun strObservable() : Observable<String> {
return Observable.just(str)
}
// defer observable
fun deferObservable() : Observable<String> {
return Observable.defer {
Observable.just(str)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.