Last active
January 17, 2019 04:24
-
-
Save vamsitallapudi/58fc0ff41c534109e28b088702655f81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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