logo
down
shadow

Make asynchronous call synchronous in Kotlin


Make asynchronous call synchronous in Kotlin

By : PHP Expert
Date : November 25 2020, 04:01 AM
fixed the issue. Will look into that further to the hint from the_dani
I managed come to the solution below using coroutines as detailed in "Wrapping callbacks" section of the Kotlin coroutines documentation:
code :
class Main {
    companion object {
        @JvmStatic

        fun main(args: Array<String>) = runBlocking {
            val result1 = Main().nonAsyncMethod1(arrayListOf(1, 2, 3, 4, 5))
            result1.elements.forEach { println(it) }
        }
    }

    class Result1(var elements: Collection<String>)

    fun asyncMethod1(x: Collection<Int>, callback: (Result1) -> Unit) {
        Thread().run {
            // do some calculation
            Thread.sleep(1000)
            callback(Result1(x.map { "\"$it\"" }.toList()))
        }
    }

    suspend fun nonAsyncMethod1(entities: Collection<Int>): Result1 = suspendCoroutine {
        cont ->
            asyncMethod1(entities) { cont.resume(it) }
    }
}


Share : facebook icon twitter icon
How can I make an asynchronous call synchronous

How can I make an asynchronous call synchronous


By : Steve Stufferberg
Date : March 29 2020, 07:55 AM
seems to work fine EDIT: stevex is absolutely right that your first priority should be to find a way just to make the whole thing asynchronous. Failing that, the answer below should achieve what you want while entrusting the synchronisation steps to the OS for optimal power usage.
Probably you want to use an NSConditionLock to lock the thing that calls assetForUrl:... immediately after the call, then have your callbacks unlock it.
code :
NSConditionLock *conditionLock; // somewhere; an instance variable

#define kYourClassInitialCondition 0
#define kYourClassWaitingCondition 1
// etc

...

[conditionLock lockWhenCondition:kYourClassInitialCondition];

[whomever assetForUrl:whatever
          resultBlock:^(args here)
                      {
                         ... do relevant immediate work here ...

                         [conditionLock lockWhenCondition:kYourClassWaitingCondition];
                         [conditionLock unlockWithCondition:kYourClassFinishedCondition];
                      }
          failureBlock:^(args here)
                      {
                         ... as above, same semantics when done ...
                      }
 ];


[conditionLock unlockWithCondition:kYourClassWaitingCondition];

[conditionLock lockWhenCondition:kYourClassFinishedCondition];
[conditionLock unlockWithCondition:kYourClassInitialCondition];
How to make an asynchronous Dart call synchronous?

How to make an asynchronous Dart call synchronous?


By : Ceremdra
Date : March 29 2020, 07:55 AM
I hope this helps . The only time that you can wrap an async method in a synchronous one is when you don't need to get a return value.
For example if you want to disable the save button, save results to the server asynchronously and re-enable the save button when the job is done you can write it like this:
code :
Future<bool> save() async {
  // save changes async here
  return true;
}

void saveClicked() {
  saveButton.enabled = false;
  save()
    .then((success) => window.alert(success ? 'Saved' : 'Failed'))
    .catchError((e) => window.alert(e))
    .whenComplete(() { saveButton.enabled = true; });
}
Future<Null> saveClicked() async {
  saveButton.enabled = false;
  try {
    bool success = await save();
    window.alert(success ? 'Saved' : 'Failed');
  }
  catch (e) {
    window.alert(e);
  }
  finally {
    saveButton.enabled = true;
  }
}
How to Make a Synchronous Call an Asynchronous Call in Angular?

How to Make a Synchronous Call an Asynchronous Call in Angular?


By : timothy buckely
Date : March 29 2020, 07:55 AM
should help you out You can wrap the stored procedure call in a promise. The browser will make the call and continue on without waiting for it to complete and you can react appropriately in the resolve or reject functions. You can use angular's $q service:
code :
insertRecord();
$q(function() {
    storedProcCall();
});
redirect();
Best way to make an asynchronous call effectively synchronous in iOS 10

Best way to make an asynchronous call effectively synchronous in iOS 10


By : Dhaval Rana
Date : March 29 2020, 07:55 AM
This might help you Your attempt to call doOtherStuff() in the completion block is a correct approach (the only other one is notifications, those are the only two options)
What is complicating it in this case is the bridging from Obj-C to Swift that is necessary. Code to do that is:
code :
let myData = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
AudioServicesAddSystemSoundCompletion(YOUR_SOUND_ID, CFRunLoopGetMain(), kCFRunLoopDefaultMode,{ (mSound, mVoid) in
        let me = unsafeBitCast(mVoid, YOURCURRENTCLASS.self)
        //me it is your current object so if yo have a variable like
        // var someVar you can do
        print(me.someVar)
    }, myData)
How to make this asynchronous call, synchronous

How to make this asynchronous call, synchronous


By : dispayOops
Date : March 29 2020, 07:55 AM
should help you out You cannot make an async call synchronous, except by blocking your code, which you do no NOT want to do. Instead, I suggest you convert geocode into a promise
Related Posts Related Posts :
  • How do I make this image larger?
  • Run icCube with JDK 10
  • Expression with Math.random() always returns the same value
  • Getting the Set with the most elements nested in a HashMap using Java Streams
  • XmlSlurper to parse XML and get value of inside elements using Groovy
  • Extracting data from HTML and formatting the output
  • SOLR documentCache JMX metrics clarification
  • Limiting Wildfly 14 Two-Way SSL to specific clients
  • How do I get Min and max values to only print when "year" is entered?
  • Hashmap can't loop - getKey() method not found - Using Java 8
  • Android Studio - Create an EditText with a click of a button
  • Mockito Test not invoking verify() method
  • Wrap method implementations of Java interfaces
  • Remediating dynamic SQL into prepared statements
  • Where do X and Y start at in swing windows
  • java code with files work from eclipse but dont work from cmd
  • Return page object from JPA query
  • I can't figure out why this code in my APCS multiple choice book returns 19
  • How to save data between methods
  • I'm trying to install Apache Gobblin. How can I install it using Gradle?
  • Spring Data Sorting Array or Set into Pageable
  • Question about the Java documentation and its implementation
  • How to make a JButton that when pressed it does a new action
  • Java hibernate No validator could be found for boolean
  • Making a POJO Thread Safe
  • Save the data of a text file in a arraylist
  • Sort a List<String[]> by indices using Comparator
  • Overloading in Java for user input?
  • Unable to format timestamp as YYYY-MM-DD HH:mm:ss in java
  • Access SQLite Helper From Adapter
  • How to stream a csv file with header to a HashMap<String, Double> in Java?
  • can't get go daddy ssl certificate to work with spring boot
  • ResourceBundle can't find BaseName gradle project java
  • Java; Jackson; Parsing the array of array json string
  • Java - map key lookup ignoring case
  • Jackson deserialize map null values to empty string
  • Anyone knows why setCount() is not working in twitter4j?
  • Object Visibility in a Multi-threaded Program in Java
  • Can't store and load an arraylist in an object file
  • convert a string number starts with `00` to `+` in java
  • Java - avoiding NonSuchElementException using ConcurrentLinkedDeque
  • Converting Immutable to mutable list Java
  • Getting nosuchmethod exception
  • How to get MQTT subscriptions
  • Android Google Sign in Exceptions
  • JavaFX - method that waits for user input
  • Replacing values for a particular key in treemap changes values for every key
  • This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter th
  • Kafka: consume all messages on demand
  • Notify what text was changed in textview
  • Tinkerpop/Gremlin: select vertices together with outgoing edge count
  • transform a list of objects into a list of integers that pass a check
  • Why this java code is showing strange behavior?
  • Maven Project classes not compiling
  • Edit image to make text more clear opencv
  • Android Spinner nullpointer
  • Add result to int array every time you finish counting the occurrence
  • Android import java library
  • How to use LDAP Authentication in a corporate environment
  • adding item during iteration in java special usecase
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org