06/25/2022, 5:01 AM
How to reflect a flow value when it gets ready after collecting?
var property: String? = null

    property = it


textView.text = property // reflect this value when its get ready
Something like that, any idea?

Erick Sumargo

06/25/2022, 7:19 AM
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?


06/25/2022, 7:27 AM
Because I have to use the
many times in multiple functions within the fragment, it's difficult for me to put all these uses inside


06/26/2022, 8:38 PM
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
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) }
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 
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.