How to reflect a flow value when it gets ready aft...
# android
a
How to reflect a flow value when it gets ready after collecting?
Copy code
var property: String? = null
.......

propertyFlow.collect{
    property = it
}

.......

textView.text = property // reflect this value when its get ready
Something like that, any idea?
e
I'm not really sure with the question, but I suppose you want your textView updated for every new emission? If so, why not move your the textView inside collect lambda then?
a
Because I have to use the
property
many times in multiple functions within the fragment, it's difficult for me to put all these uses inside
collect
.
d
One way is to use SharedFlow, there you can 'subscribe' to the flow from as many independant consumers as you want, in any time sequence. Another way, I have had success with, is much more basic, and Im not sure if this is a 'bad idea' or 'good idea' -- it does 'work for me' in the cases I considered applicable. That is to use a simple form of 'observable' -- that is not coroutine or flow based, but can be trivially hooked up to flows. Like this
Copy code
typealias Observe<T> = (T)-> Unit 
typealias Observers<T> = MutableList<Observe<T>> 
fun <T> observers() = mutableListOf<Observe<T>>()
fun <T> Observers<T>.invoke(v: T) = forEach {  it(v) }
...
Copy code
val observers = observers<String>()
...

// Anywhere its useful to be notified of a new value
// simply add a new 'observer'\ callback to the list 
    observers += { 
          textview.value = it 
    }
Copy code
Wherever the value changes .. could be in collect() 

  wherevaluechanged(v: T ) {  observers(v) } // notify all observers
This has worked well for me as long as I consistantly guaretnee that the call to observers() is on the correct thread (main/UI thread for android) -- that can be baked into the observers(T) call if needed
Where this has really helped a lot is when constructing UI elements dynamically that are in different layout order then the source of changed data. Imagine a selection/text box and multiple dependent UI elements either before or after the select box. Using the above pattern, I need only define 1 variable for observers, and use local refrences to the individual views in the place they are initialized, without needing to store them in variables, or have any centralized code that 'knows what dependant compoents' to update.
Note; :the above is similar to using shared flows, but much simplier -- and feature-less, it does NOT handle structured concurrency in any way.