Skip to content

Instantly share code, notes, and snippets.

Avatar

Toshihiko Arai araemon

View GitHub Profile
View ViewController.mm
//
// ViewController.mm
//
#import "ViewController.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
@interface ViewController ()
View ScopedAppActivity.kt
abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope by MainScope() {
override fun onDestroy() {
super.onDestroy()
cancel()
}
}
View MainActivity.kt
class MainActivity : ScopedAppActivity() {
...
}
View MainActivity.kt
launch {
// メインスレッドで実行される
var counter = 0
while (true) {
textView.text = "${++counter} $message"
delay(1000) // ブロッキングされない
}
}
View Delay.kt
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
View MainActivity.kt
button.setOnClickListener {
launch {
val deferred = async(Dispatchers.IO) {
Thread.sleep(3000)
"リクエスト No.${++requestCount}"
}
withContext(Dispatchers.Main) {
message = deferred.await()
}
}
View MainActivity.kt
var requestCount = 0
suspend fun showIOData() {
val deferred = async(Dispatchers.IO) {
Thread.sleep(3000)
"リクエスト No.${++requestCount}"
}
withContext(Dispatchers.Main) {
message = deferred.await()
}
View MainActivity.kt
var requestCount = 0
suspend fun fetchIOData():String = withContext(Dispatchers.IO) {
Thread.sleep(3000)
"リクエスト No.${++requestCount}"
}
button.setOnClickListener {
launch {
message = fetchIOData()
View MainActivity.kt
button.setOnClickListener {
launch {
message = fetchIOData()
}
}
View MainActivity.kt
fun View.onClick(action: suspend (View) -> Unit) {
val eventActor = GlobalScope.actor<View>(Dispatchers.Main, capacity = Channel.CONFLATED) {
for (event in channel) action(event)
}
setOnClickListener {
eventActor.offer(it)
}
}
You can’t perform that action at this time.