rx java2 - kotlin getting a subscriber to observe an observable using RxJava2 -
android studio 3.0 beta2
i have created 2 methods 1 creates observable , creates subscriber.
however, having issue try subscriber subscribe observable. in java work, , trying work in kotlin.
in oncreate(..) method trying set this. correct way this?
class mainactivity : appcompatactivity() { override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) setcontentview(r.layout.activity_main) /* cannot set subscriber subcribe observable */ createstringobservable().subscribe(createstringsubscriber()) } fun createstringobservable(): observable<string> { val myobservable: observable<string> = observable.create { subscriber -> subscriber.onnext("hello, world!") subscriber.oncomplete() } return myobservable } fun createstringsubscriber(): subscriber<string> { val mysubscriber = object: subscriber<string> { override fun onnext(s: string) { println(s) } override fun oncomplete() { println("oncomplete") } override fun onerror(e: throwable) { println("onerror") } override fun onsubscribe(s: subscription?) { println("onsubscribe") } } return mysubscriber } }
many suggestions,
pay close attention types.
observable.subscribe()
has 3 basic variants:
- one accepts no arguments
- several accept
io.reactivex.functions.consumer
- one accepts
io.reactivex.observer
the type you're attempting subscribe in example org.reactivestreams.subscriber
(defined part of reactive streams specification). can refer docs fuller accounting of type, suffice it's not compatible of overloaded observable.subscribe()
methods.
here's modified example of createstringsubscriber()
method allow code compile:
fun createstringsubscriber(): observer<string> { val mysubscriber = object: observer<string> { override fun onnext(s: string) { println(s) } override fun oncomplete() { println("oncomplete") } override fun onerror(e: throwable) { println("onerror") } override fun onsubscribe(s: disposable) { println("onsubscribe") } } return mysubscriber }
the things changed are:
- this returns
observer
type (instead ofsubscriber
) onsubscribe()
passeddisposable
(instead ofsubscription
)
.. , mentioned 'vincent mimoun-prat', lambda syntax can shorten code.
override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) setcontentview(r.layout.activity_main) // here's example using pure rxjava 2 (ie not using rxkotlin) observable.create<string> { emitter -> emitter.onnext("hello, world!") emitter.oncomplete() } .subscribe( { s -> println(s) }, { e -> println(e) }, { println("oncomplete") } ) // ...and here's example using rxkotlin. named arguments // give code little more clarity observable.create<string> { emitter -> emitter.onnext("hello, world!") emitter.oncomplete() } .subscribeby( onnext = { s -> println(s) }, onerror = { e -> println(e) }, oncomplete = { println("oncomplete") } ) }
i hope helps!
Comments
Post a Comment