kotlin - Android LiveData Observer not active after first update -
i'm trying out basic implementation of architecture component's live data kotlin this:
class marketfragment : lifecyclefragment(){ ...... override fun onactivitycreated(savedinstancestate: bundle?) { super.onactivitycreated(savedinstancestate) viewmodel=viewmodelproviders.of(this).get(marketviewmodel::class.java) viewmodel.book?.observe(this, observer { book-> //updateui }) .... my viewmodel class created this:
class marketviewmodel : viewmodel() { var book: mutablelivedata<book>? =mutablelivedata() var repository: repository?= repository() init { update("parameter") } fun update(s: string) { book=repository?.getbook(s) } } and repository:
fun getbook(booksymbol:string):mutablelivedata<book> { val book=mutablelivedata<book>() ...... call . enqueue (object : callback<book> { override fun onresponse(call: call<book>?, response: response<book>?) { book.value=response?.body() } ..... }) return book } }
and of works great , ui updated should first time. if try make manual calls update viewmodel ui action, retrofit call still works expected new data not sent observer in fragment:
//this doesn't work: viewmodel.update("string") //this returns false: viewmodel.book.hasactiveobservers() is expected behaviour observer become inactive after first trigger?
you creating new mutablelivedata instance each time calling getbooks
hence observer not observing right livedata anymore.
to solve this, viewmodel should keep 1 mutablelivedata instance , post updates using postvalue function.
the repository can use rxjava (flowable) execute query on background thread , return observable<book> (or single<book>)
Comments
Post a Comment