#postvalue
Explore tagged Tumblr posts
Text
android jetpack livedata postValue(), setValue()
original source :Ā https://blog.mindorks.com/livedata-setvalue-vs-postvalue-in-android
we can change the UI of an application when there is a change in some data.Ā
livedata넼 ķµķ“ ģ½ź² ė°ģ“ķ° ė³ź²½ģ uiģ ģ ģ©ķ ģ ģė¤.
livedata ģ¤ėŖ
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services.
In a simple way, LiveData is basically a data holder and it is used to observe the changes of a particular view and then update the corresponding change.
So, LiveData is used to make the task of implementing ViewModel easier. The best part about LiveData is that the data will not be updated when your View is in the background and when the view will come in the foreground, then it will get the updated data only.
Difference between setValue() and postValue()
either you can update the data on the Main thread or you can update the data using the background thread. So, the use-case of setValue and postValue depends on these two situations only.
While using the Main thread to change the data, you should use theĀ Ā setValueĀ Ā method of the MutableLiveData class and while using the background thread to change the LiveData, you should use theĀ Ā postValueĀ Ā method of the MutableLiveData class.
So, the duty of theĀ Ā postValueĀ Ā method is to post or add a task to the main thread of the application whenever there is a change in the value. And the value will be updated whenever the main thread will be executed (ģ¬źø°ģ mainthreadź° ģ¤ķė ė ģ“ė¶ė¶ģ“ ģ¤ģķ ė¶ė¶). So, basically, it is requesting the main thread to set the new updated value and then notify the observers.
While the setValue method is used to set the changed value from the main thread and if there are some live observers to it, then the updated value will also be sent to those observers as well. This setValue method must be called from the main thread.
So, here are some of the points that you must think before using setValue and postValue:
If you are working on the main thread, then both setValue and postValue will work in the same manner i.e. they will update the value and notify the observers.
If working in some background thread, then you can't use setValue. You have to use postValue here with some observer. But the interesting thing about postValue is that the value will be change immediately but the notification that is to be sent to observers will be scheduled to execute on the main thread via the event loop with the handler.
Letās take an example,
// setValue liveData.setValue("someNewData") liveData.setValue("againNewData") // postValue liveData.postValue("someNewData") liveData.postValue("againNewData")
In the above example, the setValue is called from the main thread and the postValue is called from some background thread.
Since the setValue is called twice, so the value will be updated twice and the observers will receive the notification regarding the updated data twice.
But for postValue, the value will be updated twice and the number of times the observers will receive the notification depends on the execution of the main thread. For example, if the postValue is called 4 times before the execution of the main thread, then the observer will receive the notification only once and that too with the latest updated data because the notification to be sent is scheduled to be executed on the main thread. So, if you are calling the postValue method a number of times before the execution of the main thread, then the value that is passed lastly i.e. the latest value will be dispatched to the main thread and rest of the values will be discarded.
Another thing to care about postValue is that, if the field on which the postValue is called is not having any observers and after that, you call the getValue, then you will not receive the value that you set in the postValue because you don't have an observer here.
0 notes
Text
9 Suggestions For Getting The Most From Your Conference Investment
You can utilize these sites to get much needed direct exposure for your online business. You can also utilize it to catch multiple market sections. You can almost do anything with it, and by now, you need to include it to your marketing and marketing strategies. You can follow the top 6 suggestions to begin your extremely own successful social networking.
youtube
You have to beware with this. Not all online forum admins let advertisements in their online forum, so be sure to read the forum guidelines prior to marketing. I recommend you look for forums in your specific topic, where signitures are permitted, and you can put you ad therein without braking the rules. new link popularity career advice new link popularity career advice If you postvaluable messages in the online forum, this can offerverycertified traffic especially.
youtube
There is no proof to show this. Hair development takes place in the hair follicle so any accelerating of hair development would be due to changes in the hair follicle. Quality link appeal can not only get you listed in the link popularity advertising tips majoronline search engine without you ever having actuallysubmitted your website, but it will assist your sitemove up in the online search engine result rankings too. Pointer 7. Start Your Own Newsletters If you desire todevelop relationship with your client, or reallywant togenerate income online, a great newsletter will help you. You can send out your newsletter weekly, bi-weekly. Do not sendas soon as a month given that the time span is too long, individualsmight forget you. When trend link popularity productivity confronted with a number ofoptions, the majority ofclients have problem making a clear decision. They typicallyrespond by procrastinating - and nevermaking a decision.You lose a sale you currently had when this occurs. Relate to other websites. As you know, link appeal is among the crucial elements that search engine are checking out when they rank websites. If you want to bring up your ranking ensure you have links originating from developed websites, publishing websites, and forums. If http://www.virtuellement.com/OC/emploi-metiers-de-la-forme/asigo-system-review-publishing-press-releases-helps-your-seo.html don't target your website, promos and everything else you do online to the ideal market you're just losing your time. There's no sense sending an e-mail promotion to an organisation professional on a brand-new knitting pattern. You need to figure out precisely who your target market is: Where do they live? What do they do? How do they do it? Just how much do they make? What do they purchase? Where do they buy it? The more particular you can be in targeting your audience, the more reliable your promotions will be. It is likewise essential that you re-invest a portion of your revenues into your business! That way, not only will your business continue to grow, but its DEVELOPMENT RATE will likewise increase! This in turn generates MORE revenues, which enables you to invest MORE into your business. Do you see a pattern!?
0 notes
Text
LiveDataReactiveStreams: Where RxJava meets LiveData
When choosing a library to make your Android application reactive, which do you choose: the trusty, ever-popular RxJava 2, or the newer, first-party LiveData? While it may be a subject of debate, the good news is that these two can work together using a tool called LiveDataReactiveStreams.
In this post, weāll explore how LiveDataReactiveStreams works, as well why (or why not) you might want to use it to bring RxJava and LiveData together. Note that it does assume some familiarity with RxJava and LiveData.
Syntax
LiveDataReactiveStreams is a class provided as part of Googleās Jetpack components. To use it, you need to add the ReactiveStreams dependency to your project. In your build.gradle file, add the following to your dependencies block (replacing $lifecycleVersion with the latest dependency version, which is 2.0.0 as of this writing):
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
In order to convert from an RxJava stream to a LiveData object, use the fromPublisher() method provided by LiveDataReactive streams, like so:
// Note, I've added explicit types for clarity. You can omit these in your code. val myRxStream: Flowable<MyDataType> = Flowable.fromCallable{ fetchSomeDataViaNetworkCall() } val myLiveData: LiveData<MyDataType> = LiveDataReactiveStreams.fromPublisher(myRxStream)
The fromPublisher() method takes an instance of the Publisher interface, which is implemented by RxJava Flowables, and returns a LiveData object. Also note that the type emitted by the RxJava stream (in this case, MyDataType) will be the type of the data held by the LiveData.
Importantly, what this does is it creates a LiveData object that updates its value any time the source RxJava stream emits a new item. This means that anything that observes the LiveData (such as a Fragment that updates the UI when the LiveData changes) will be notified when the RxJava stream emits.
But⦠why?
You might be wondering the benefit of converting like this as opposed to using your RxJava stream or your LiveData object all the way through. The answer is that doing so allows us to utilize the strengths of both in a fluid way.
In terms of strengths, RxJava is a robust toolset. There are tons of operators to allow you to manipulate your data stream in a multitude of ways, including built-in tools for specifying which threads operators execute on. This is great for complex operations on data, such as might be found in the business logic of applications.
While LiveData has a smaller set of operators, it offers the benefit of built-in lifecycle awareness. This means that it can safely and easily update UI elements even through the complex lifecycles of Activities and Fragments, which is not built in to RxJava (though there are tools like AutoDispose that can make this somewhat more automatic).
Also unlike RxJava, LiveData works with data binding out of the box.
What all of this means is that LiveData is great for pushing data to the UI but not as much for handling business logic, and RxJava is great for business logic but not as much for UI. The LiveDataReactiveStreams fromPublisher() method offers a simple way for us to push updates from our data/business-logic layers up to the UI while utilizing these strengths.
When used in this way, a cool feature of LiveDataReactiveStreams is that it automatically posts values to the main thread. If youāre using LiveData for updating UI elements, this saves you from having to manually call postValue() on a LiveData or use RxAndroid for returning to the main thread on the RxJava stream.
Finally, a key selling point of LiveDataReactiveStreams is that is a more direct way of connecting RxJava and LiveData together. Without it, you need to subscribe to your RxJava chain and post values to the LiveData in the subscriber:
// Private, mutable backing field - only update values internally private val _myLiveData = MutableLiveData<String>() // Observers will subscribe to this since it is immutable to them val myLiveData: LiveData<String> get() = _myLiveData // Keep a reference to the disposable, and make sure to clear it appropriately somewhere val disposable: Disposable = Flowable.fromCallable{ methodThatReturnsString() } .subscribe( { myString -> _myLiveData.postValue(myString) }, // Make sure to handle errors { error -> Log.e(TAG, "Oops, hit an error", error) } )
While this certainly works, calls to subscribe() feel like that youāre ending your RxJava chain and leaving the reactive world, even though youāre still trying to do reactive things with LiveData. LiveDataReactiveStreams bridges that gap so that you donāt have to leave the reactive world.
Caveats
While this tool offers simplicity in some ways, it also comes with a handful of limitations that you will want to consider. You can find a few major ones discussed below.
Error Handling
To start with, since LiveData does not have the option to add an onError handler like RxJava does, any errors that make it through LiveDataReactiveStreams from your RxJava stream will crash your application. That being said, you can use RxJavaās error handling operators in your RxJava chain to prevent this:
// Note, I've added explicit types for clarity. You can omit these in your code. val myRxStream: Flowable<Int> = Flowable.fromCallable{ methodThatThrowsAnError() } .onErrorReturnItem(-1) // Use -1 as a error case val myLiveData: LiveData<Int> = LiveDataReactiveStreams.fromPublisher(myRxStream)
Subscriptions and Lifecycles
Another major caveat lies in how the LiveData subscribes to the RxJava stream behind the scenes. When the LiveData becomes inactive because the lifecycle it is associated with moves to the DESTROYED state, then LiveData clears its subscription from the RxJava stream. It will then re-subscribe when the LiveData becomes active again. This has different implications depending on whether you are using hot vs. cold Flowables.
For cold Flowables, such as the one in the example above, the RxJava stream will start all over again when the LiveData re-subscribes. If this RxJava stream makes a network request, this means that the request will be made again when reattaching (unless you have some kind of caching mechanism in place).
For hot Flowables which can emit even with no subscribers, this has the implication that any emissions sent out after the LiveData becomes inactive will not be picked up by the LiveData.
In both cases, LiveData will still cache the last value emitted by the RxJava stream and send it to the Observer when it becomes active again, but wonāt get an updated value until the stream emits another item.
Whether this behavior is problematic depends on your use case. In the end, with mindful use of RxJava features, you can still accomplish your desired flow. The key is being aware of how the lifecycle affects your subscription.
What about toPublisher()?
Astute readers may have noticed another method provided by LiveDataReactiveStreams called toPublisher(). Since weāre focusing on using LiveData to push data to the UI, fromPublisher() is sufficient to get the benefits of LiveData and RxJava together. However, I encourage you to learn more about toPublisher() if it seems like it fits your use-case.
Reactive Choices
When it comes to choosing whether to use RxJava or LiveData in your next project, keep in mind that they can work well together in the same codebase. As weāve discussed, they have their individual strengths, and can work really well with the style of MVVM laid out by Google.
LiveDataReactiveStreams offers a simple interface that allows you to convert RxJava streams to LiveData in a direct way. However, keep in mind the slew of caveats that come with it. These caveats can bring their own complexity, so consider them when deciding if LiveDataReactiveStreams will work best for your situation.
LiveDataReactiveStreams: Where RxJava meets LiveData published first on https://johnellrod.weebly.com/
0 notes