Home > Enterprise >  Kotlin, Java - Call a function but postpone its execution until another function has been called
Kotlin, Java - Call a function but postpone its execution until another function has been called

Time:10-16

I'm building a RecyclerView in an Android app and I inflate its items asynchronously (I inflate a Framelayout synchronously and right after I call the asynchronous inflation of the "real" view). The RecyclerView could call onBindViewHolder before that asynchronous inflation has finished to execute.

So the behaviour I want is the following: Function A gets called once. If function B has been executed, A starts to execute. But if function B has not been executed yet, then A will start its execution right after B finished to execute. Things to consider: There is a callback when B finishes to execute and it happens on the same thread where A gets called. Both A and B are methods of the object x let's say.

Some ideas on how I can achieve what I want?

CodePudding user response:

Using coroutines:

val bHasBeenCalled = Job()
fun a() {
  scope.launch {
    bHasBeenCalled.join()
    doA()
  }
}
fun b() {
  doB()
  bHasBeenCalled.complete()
}
  • Related