スポンサーリンク

【Kotlin】Flowの.catchか従来のtry-catchか

スポンサーリンク

Flow .catch

FlowのcatchはSuspend FunctionのCancellationExceptionをcatchしません.すなわち,Flow内のSuspend Functioniは通常通りCancelすることが可能です.

try-catch

try-catchはCancellationExceptionをcatchしてしまいます.そのため,通常はCancellationExceptionのみthrowするように冗長なコードを記載する必要があります.

try{
    //do something
}catch(e: Exception){
    if(e is CancellationException) throw e // only throw CancellationException
    //do something when error
}

なのでFlowと併用する場合には,Flow.catchを使用するほうが楽に可読性があがります

タイトルとURLをコピーしました