Usman Saeed
Usman Saeed

Reputation: 51

Unable to create Observable in Kotlin

I am trying to create Observable in kotlin .But its giving error unresolved reference on OnSubscribe method

  fun getDisposableObserver(): Observable<Background> {

        return Observable.create(object :Observable.OnSubscribe<Background> ->{})
    }

I tried this snippet .It also does not work

  Observable.create(object : ObservableOn.OnSubscribe<Int> {
            override fun call(subscriber: Subscriber<in Int>) {
                for(i in 1 .. 5)
                    subscriber.onNext(i)

                subscriber.onCompleted()
            }
        })

What i am doing wrong ?,How can i create Observable?

Upvotes: 0

Views: 1319

Answers (3)

Matteo Pasotti
Matteo Pasotti

Reputation: 79

I don't know if you are using Architecture Components, but if i want to observe Background i think that MutableLiveData and LiveData could help

private val _background = MutableLiveData<Background>()
val background: LiveData<Background> = _background

fun editBackground(newBackground : Background) {
   _background.postValue(newBackground)
}

Put this code inside a ViewModel or a Presenter. Then in your View (Activity/Fragment) you can observe background in this way

viewModel.background.observe(this, Observer { newValue ->

        })

Upvotes: 0

Demigod
Demigod

Reputation: 5635

If you want to control the items emission by your self, you can create an Observable with .create method, like this

    Observable.create({ e: ObservableEmitter<String> -> e.onNext("") })

    Observable.create(object: ObservableOnSubscribe<String> {
        override fun subscribe(e: ObservableEmitter<String>) {
            e.onNext("")
        }
    })

But in this case you will have to call onNext, onComplete, onError by your own.

But if you want a much simpler solution, you can create it like

Observable.just(1)

Observable.fromCallable { 1 }

Upvotes: 5

Stanislav Mukhametshin
Stanislav Mukhametshin

Reputation: 853

Simple example with ObservableEmitter

    val obs = Observable.create<Int> {
        for(i in 1 .. 5)
            it.onNext(i)

        it.onComplete()
    }

Upvotes: 1

Related Questions