Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
M
Mirai
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Locked Files
Issues
0
Issues
0
List
Boards
Labels
Service Desk
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Security & Compliance
Security & Compliance
Dependency List
License Compliance
Packages
Packages
List
Container Registry
Analytics
Analytics
CI / CD
Code Review
Insights
Issues
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
MyCard
Mirai
Commits
f72d73b1
Commit
f72d73b1
authored
Nov 02, 2019
by
Him188
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add SuspendLazy
parent
7842ce31
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
45 additions
and
0 deletions
+45
-0
mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt
...rc/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt
+45
-0
No files found.
mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt
0 → 100644
View file @
f72d73b1
@
file
:
Suppress
(
"unused"
,
"FunctionName"
)
package
net.mamoe.mirai.utils
import
kotlinx.coroutines.CompletableDeferred
import
kotlinx.coroutines.CoroutineScope
import
kotlinx.coroutines.Deferred
import
kotlinx.coroutines.async
import
net.mamoe.mirai.contact.QQ
/**
* 创建一个在当前 [CoroutineScope] 下执行的 [SuspendLazy]
*/
fun
<
R
>
CoroutineScope
.
SuspendLazy
(
initializer
:
suspend
()
->
R
):
SuspendLazy
<
R
>
=
SuspendLazy
(
this
,
initializer
)
/**
* 挂起初始化的 [lazy], 是属性不能 `suspend` 的替代品.
*
* 本对象代表值初始化时将会通过 [CoroutineScope.async] 运行 [initializer]
*
* [SuspendLazy] 是:
* - 线程安全
* - 只会被初始化一次.
* - `SuspendLazy<R>.value` 返回 `Deferred<R>`
* - 可以用作属性代表 (`val profile: by SuspendLazy(GlobalScope) { calculateValue() }`)
*
* @sample QQ.profile
*/
class
SuspendLazy
<
R
>(
scope
:
CoroutineScope
,
val
initializer
:
suspend
()
->
R
)
:
Lazy
<
Deferred
<
R
>>
{
private
val
valueUpdater
:
Deferred
<
R
>
by
lazy
{
scope
.
async
{
initializer
()
}
}
@Suppress
(
"EXPERIMENTAL_API_USAGE"
)
override
val
value
:
Deferred
<
R
>
get
()
=
if
(
isInitialized
())
{
CompletableDeferred
(
valueUpdater
.
getCompleted
())
}
else
{
CompletableDeferred
<
R
>().
apply
{
valueUpdater
.
invokeOnCompletion
{
this
.
complete
(
valueUpdater
.
getCompleted
())
}
}
}
override
fun
isInitialized
():
Boolean
=
valueUpdater
.
isCompleted
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment