简体   繁体   中英

How to emit values from different functions, but collect all of them in one place? Flow Kotlin

In my activity I need to emit different flow values on callbacks like:

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    emit(1)
  }


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    emit(1)
}

and collect in another class like:

collect{value->
  when(value){
    1->..
    2->..
  }
}

is it possible?

How about this?:

Make an interface to notify on every callback, overridden method, etc. you need:

interface Notifier<T> {
    fun notify(t: T)
}

Inside your class declare an object to implement that interface:

private var notifier: Notifier<Int>? = null

Also declare a Flow with the callbackFlow builder where you will initialize the notifier object:

val myFlow = callbackFlow<Int> {
    notifier = object: Notifier<Int> {
        override fun notify(t: Int) {
            launch {
                channel.send(t)
            }
        }
    }
    awaitClose()
}

Inside your methods notify your data:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    notifier?.notify(1)
}


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    notifier?.notify(2)
}

And finally consume the Flow like this:

val job = launch(Dispatchers.Default) {
    myClassReference.myFlow
        .collect {
            when(it) {
                1 -> { println("It's one") }
                2 -> { println("It's two") }
            }
        }
}

And make sure to cancel job properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM