Advertisement
Guest User

Kotlin Async/Await

a guest
Jul 15th, 2016
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. package com.example.myapplication
  2.  
  3. import android.os.Bundle
  4. import android.os.Handler
  5. import android.os.Looper
  6. import android.support.v7.app.AppCompatActivity
  7. import android.widget.TextView
  8. import java.net.URL
  9.  
  10. class MainActivity : AppCompatActivity() {
  11.  
  12.     override fun onCreate(savedInstanceState: Bundle?) {
  13.         super.onCreate(savedInstanceState)
  14.         setContentView(R.layout.activity_main)
  15.  
  16.         val text1 = findViewById(R.id.text1) as TextView
  17.         val text2 = findViewById(R.id.text2) as TextView
  18.  
  19.         async { // C# Style
  20.             try {
  21.                 text1.text = await(URL("https://fb.com/")
  22.                     .readTextAsync()) // Асинхронный запрос
  23.                     .getTitle()
  24.                     .toUpperCase()
  25.             } catch (e: Exception) {
  26.                 text1.text = "ERROR: $e"
  27.             }
  28.         }
  29.  
  30.         async { // Monad Style
  31.             text2.text = URL("https://ru.wikipedia.org/")
  32.                 .readTextAsync() // Асинхронный запрос
  33.                 .than { it.getTitle() }
  34.                 .than { it.toUpperCase() }
  35.                 .onError { "ERROR: $it" }
  36.         }
  37.     }
  38.  
  39.     private fun String.getTitle() = Regex("<title>(.+?)</title>").find(this)!!.groupValues[1]
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement