kotlin 協程方式使用datastore

2021-10-25 15:18:22 字數 2115 閱讀 5875

環境: as 3.6.3, gradle 5.6.4, jdk8, kotlin 1.4.10

1 build.gradle

dependencies 

// 單獨使用協程時,下面依賴必備

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'

}

2 引用官方**,寫乙個計算器,類和業務**一頁過。

// import 自己用(alt+shift+enter)引入

class mainactivity :()

}

btn2.

setonclicklistener}}

}//// @internalcoroutinesapi

// override fun ondestroy()

}// 乙個靜態封裝類

object datastoreutils

suspend

funwrite

(context: context, num: int)

}fun

read

(context:context)

: flow

}}

3 布局檔案放乙個textview,兩個button用來顯示和操作

<?xml version="1.0" encoding="utf-8"?>

xmlns:android

=""=""

xmlns:tools

=""android:layout_width

="match_parent"

android:layout_height

="match_parent"

tools:context

=".mainactivity"

>

android:id

="@+id/txt1"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:text

="hello activity!"

="parent"

="parent"

="parent"

/>

android:id

="@+id/gl1"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:orientation

="horizontal"

="50dp"

/>

android:id

="@+id/btn1"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

="parent"

="@id/gl1"

="@id/btn2"

android:text

="count"

/>

android:id

="@+id/btn2"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

="parent"

="@id/gl1"

="@id/btn1"

android:text

="result"

/>

androidx.constraintlayout.widget.constraintlayout

>

Kotlin協程筆記

會阻塞主線程,等待協程執行完,才會繼續執行主線程 不會阻塞主線程,返回job型別的物件 var job globalscope.launch 3 async 用於啟動乙個非同步協程任務,與launch用法基本一樣,不阻塞執行緒,區別在於 async的返回值是deferred,將最後乙個封裝成了該物件...

Kotlin協程快速入門

協程,全稱可以譯作協同程式,很多語言都有這個概念和具體實現,之前入門python的時候接觸過,而kotlin其實也早就有這個擴充套件功能庫了,只不過之前一直處於實驗階段,不過前段時間1.0的正式版終於出了,網上的相關部落格也多了起來,經過這幾天的學習我也來做下小結吧。首先貼下kotlin協程的官方g...

Kotlin 協程學習記錄

kotlin 協程 implementation org.jetbrains.kotlinx kotlinx coroutines core 1.2.1 1 runblocking 會一直阻塞到塊中的 執行完 runblocking job.join 等待直到子協程執行結束 主協程與後台作業的持續時...