-
Notifications
You must be signed in to change notification settings - Fork 0
Create Simple observable
Devrath edited this page Dec 29, 2023
·
1 revision
class MyObservable {
fun createStringObservable(inputString: String): Observable<String> {
return Observable.create { emitter ->
// Emit the input string to observers
emitter.onNext(inputString)
// Complete the observable (optional)
emitter.onComplete()
// Clean up resources if needed (optional)
emitter.setCancellable {
// Dispose or release resources here
}
}
}
}
fun main() {
// Example of using the observable
val myObservable = MyObservable()
val disposable = myObservable.createStringObservable("Hello, RxJava!")
.subscribe(object : Observer<String> {
override fun onSubscribe(d: Disposable) {
// Called when the subscription is established
}
override fun onNext(t: String) {
// Called when a new string is emitted
println("Received: $t")
}
override fun onError(e: Throwable) {
// Called when an error occurs
}
override fun onComplete() {
// Called when the observable completes (optional)
}
})
// Dispose the subscription when it's no longer needed (e.g., in onDestroy of an Android component)
disposable.dispose()
}
