我是 Kotlin 的新手,來自 Java Spring 世界。我希望在 Kotlin 中復制 Java 功能,這是每個請求模型的普通執行緒。查看下面的 Kotlin 示例,我看到其中一種方法默認為 flow,而對于其他方法,他們指定了暫停。我已經閱讀了檔案,但仍然有點困惑。我有幾個問題要檢查我的理解:
- 有什么好的理由在 Kotlin 中為每個請求模型強制一個執行緒?
- 要強制每個請求模型一個執行緒,所有函式都需要是掛起型別嗎?
- 如果我遵循典型的 spring 范例*,我是否應該擔心使用型別流標記所有功能?
*不包括服務類中的狀態
@RestController
class UserController(private val userRepository: UserRepository) {
@GetMapping("/")
fun findAll(): Flow<User> =
userRepository.findAll()
@GetMapping("/{id}")
**suspend** fun findOne(@PathVariable id: String): User? =
userRepository.findOne(id) ?:
throw CustomException("This user does not exist")
@PostMapping("/")
**suspend** fun save(user: User) =
userRepository.save(user)
}
uj5u.com熱心網友回復:
有什么好的理由在 Kotlin 中為每個請求模型強制一個執行緒?
沒有充分的理由不這樣做,而且通常更容易。
要強制每個請求模型一個執行緒,所有函式都需要是掛起型別嗎?
不,您可以從掛起函式呼叫普通函式,而且很可能會。只是不要阻止。
如果我遵循典型的 spring 范例*,我是否應該擔心使用型別流標記所有功能?
通常,您應該只在函式實際執行異步操作時才將其標記為掛起,例如進行 RPC。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524818.html
