network 요청에 suspend fun을 쓰는 이유

갓김치·2024년 11월 28일
0

Android

목록 보기
2/5
@HiltViewModel
class LoginViewModel @Inject constructor() : ViewModel() {

    suspend fun login(
        username: String,
        password: String,
        context: Context
    ) {
    // ...
    }
}

Network requests are typically asynchronous and time-consuming, so marking the function suspend allows it to execute without blocking the thread it runs on. The coroutine will handle pausing and resuming the function execution, ensuring smooth performance, especially on the main thread. (-> this is the reason why login function should be called in coroutineScrope.launch)

If login were a regular fun, the network call would block the thread until it completes, potentially freezing the UI in a real application.

profile
갈 길이 멀다

0개의 댓글