Trong redux-saga, bạn có thể thực hiện các nhiệm vụ (task) nền non-block, bằng 2 hiệu ứng (effect), là Fork và Spawn. Vậy làm sao để phân biệt Fork và Spawn trong redux-saga
- Fork được sử dụng để tạo nhiều task nền, được đính kèm với task cha.
- Spawn cũng giống như fork, nó khác ở chổ là tạo ra cái task nền tách rời với task cha.
Bạn xem ví dụ sau để phân biệt 2 effects trên:
const { delay, runSaga } = require("redux-saga"); const fetch = require("node-fetch"); const { fork, spawn, call, put} = require("redux-saga/effects"); function* fetchResource(resource) { console.log(`Fetch ${resource} start`); const response = yield call(fetch, "https://jsonplaceholder.typicode.com" + resource); const text = yield call(response.text.bind(response)); console.log(`Fetch ${resource} end`); } function* fetchAll() { console.log("Fork or Spawn start"); // this is pseudo code, I mean here that you can use either // fork or spawn, check results below const task1 = yield fork||spawn(fetchResource, "/posts/1"); const task2 = yield fork||spawn(fetchResource, "/posts/2"); console.log("Fork or Spawn end"); } function* main() { console.log("Main start"); yield call(fetchAll); console.log("Main end"); } runSaga({}, main);
Link sanbox: https://codesandbox.io/s/l2z7l95xjl, thay fork và spawn để xem kết quả nhé.
Kết quả khi sài fork và spawn:
// RESULTS WITH FORK(): | RESULTS WITH SPAWN(): // | // Main start | Main start // Fork start | Spawn start // Fetch /posts/1 start | Fetch /posts/1 start // Fetch /posts/2 start | Fetch /posts/2 start // Fork end | Spawn end // Fetch /posts/2 end | Main end <-- // Fetch /posts/1 end | Fetch /posts/2 end // Main end <-- | Fetch /posts/1 end
Vậy đính kèm và tách rời với task cha là gì. Nghĩa là:
- Fork: khi các task nền đang chạy, task cha phải đợi nó chấm dứt thì mới chấm dứt, hoặc khi ta huỷ (cancel) task cha, thì task con cũng kết thúc theo.
- Ngược lại khi sài spawn thì thì các task con chạy tách rời, không bị ảnh hưởng bởi task cha. Task cha không đợi nó kết thúc hay có huỷ task cha thì task con vẫn chạy bình thường.
Tham khảo thêm: https://redux-saga.js.org/docs/advanced/ForkModel.html