jmtt89
jmtt89

Reputation: 322

How bypass NetworkOnMainThreadException on Kotlin

Hi i starting with kotlin, now Android Studio 3.0 support it, but i don't know how do a simple Network request in another thread...

in java is very easy

new Thread(new Runnable() {
    @Override
    public void run() {
        //Do dome Network Request

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Update UI
            }
        });
    }
}).start();

i know i can do a AsyncTask and blablabla... but i don't want that. I want a simple solution without creating extra classes and complex use case

Is this possible in Kotlin?

Upvotes: 11

Views: 16457

Answers (1)

James McCracken
James McCracken

Reputation: 15766

All of the same classes and methods from Java and the Android SDK are available in Kotlin, so you can just use the exact same thing. The formatting is a bit nicer because of support for SAM constructors among other things.

Thread({
    //Do some Network Request

    runOnUiThread({
        //Update UI
    })
}).start()

Upvotes: 27

Related Questions